使用mybatis-plus能够节省很多sql代码的书写,也能使sql变得更加灵活,在对于比较复杂或者多表操作时,使用basemapper的sql方法不太能达到业务逻辑的需求,需要自定义sql,但是也要保证sql的灵活性。
最近在写业务的时候遇到一些坑,现在把遇到的相关问题和解决方案分享一下:
1.select中操作
方法添加参数: @Param(Constants.WRAPPER)
IPage<Vo> Method(IPage<Object> page, @Param(Constants.WRAPPER) Wrapper query);
在mapper文件中对应位置添加 ${ew.customSqlSegment}
<select id="speciesfishList" resultMap="speciesfishMap" parameterType="map">
select fc.*,fs.*
from fd_cultivation as fc
left join fd_cultivation_species as fs on fc.id = fs.cultivation_id
<if test="ew.emptyOfWhere == false">
${ew.customSqlSegment}
</if>
</select>
测试使用:
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.eq("is_deleted", 0);
queryWrapper.eq("cultivation_type", "种鱼");
cultivationSpeciesMapper.speciesfishList(Condition.getPage(query), queryWrapper);
控制台打印的sql:
Execute SQL : select fc.id, fc.area_id, fc.father_count, fc.mother_count, fc.create_user , fc.create_time, fs.father_no, fs.mother_no, fs.average_weight, fs.species_img , fc.mother_count + fc.father_count as total from fd_cultivation fc left join fd_cultivation_species fs on fc.id = fs.cultivation_id
where father_no = '1' and area_id = '2' and average_weight >= '4' and is_deleted = 0 and cultivation_type = '种鱼'
limit 2, 2
2.UpdateWrapper操作
在mapper文件中修改和添加 ${ew.sqlSet}
<update id="updateSpeciesFish" parameterType="map">
update fd_cultivation as fc LEFT JOIN fd_cultivation_species as fs
on fc.id = fs.cultivation_id
set
${ew.sqlSet}
where fc.id = #{id}
</update>
在方法中添加 @Param(“ew”)
int updateSpeciesFish(@Param("ew") UpdateWrapper query, Long id);
使用:
UpdateWrapper updateWrapper = new UpdateWrapper<>();
updateWrapper.set(ChangeStr(field.getName()), field.get(fishUpdateVo));
cultivationSpeciesMapper.updateSpeciesFish(updateWrapper, fishUpdateVo.getId());
控制台打印的sql:
Execute SQL : update fd_cultivation fc left join fd_cultivation_species fs on fc.id = fs.cultivation_id
set area_id = 2, father_no = 1, mother_no = 2, father_count = 51, mother_count = 55, average_weight = 4.0, species_img = 'asdasjkld'
where fc.id = 1552553355042705410