如果要写复杂的sql语句,使用xml写自定义SQL比较合适。
数据库:Oracle
步骤
1、controller.java文件
/**
* 根据人员id获取人员信息
*
* @param ids
* @return
*/
@PostMapping("/getUserListByIds")
public List<TrainUserEntity> getUserListByIds(List<String> ids) {
return trainService.getUserListByIds(ids);
}
2、service.java文件
/**
* 根据人员id查询人员信息
*
* @param ids
* @return
*/
List<TrainUserEntity> getUserListByIds(List<String> ids);
3、mapper.java文件
在resource文件夹-mapper文件夹(没有则创建)下,增加xml文件(此处使用TrainMapper.xml)
在TrainMapper.java文件中,增加以下代码:
/**
* 根据人员id查询人员信息
*
* @param ids
* @return
*/
List<TrainUserEntity> getUserListByIds(@Param("ids") List<String> ids);
这个时候代码会报错,
此时直接点击Generate statement,就会自动在对应的TrainMapper.xml中生成对应方法的xml语句(SQL语句是空的)。
根据自己的业务完善sql语句。
4、serviceImpl.java文件
在TrainServiceImpl.java文件中,调用mapper.xml的sql语句方法。
使用XML自定义SQL语句
1、简单查询
<select id="getByName" resultMap="userEntityMap">
select * from user where user_name = #{name}
</select>
2、模糊查询-LIKE
<select id="getByName" resultMap="userEntityMap">
select *
from train_user
where user_name LIKE CONCAT('%', CONCAT(#{name}, '%'))
</select>
3、IN
in后括号中的参数个数有限制,Oracle 9i 中个数不能超过256,Oracle 10g个数不能超过1000。
此处的解决方案:对参数进行处理,分成多个in,其中每个in列表中参数都小于1000,
<!-- getUserListByIds:对应mapper文件的方法名-->
<!-- resultType:结果的返回类型-->
<select id="getUserListByIds" resultType="com.train.mybatisplus.domain.TrainUserEntity">
select * from user
<where>
<!--ids对应mapper方法的入参名称-->
<if test='ids != null and ids.size() > 0'>
AND id IN
<foreach index="index" collection="ids" item="userid" open="(" separator="," close=")">
<if test="(index % 999) == 998">
NULL) OR id IN (
</if>
#{userid}
</foreach>
</if>
</where>
</select>
生成SQL:
结果: