MyBatis-plus自己寫sql語句
MyBatis-plus是一款很好用的工具,集成了豐富的增刪改查各種業務操作,更加方便了程序員專注於業務代碼
那麼,如果需要重寫mybatis-plus裏面的sql語句呢
比如,我需要用到多表聯合查詢,一次查詢完成封裝到實體類
實體類
如果我們多表聯合查詢,會需要查到其他表的字段,我們需要把這些字段也封裝到實體類,並註明不是該表的字段
@TableName("comment")
public class CommentEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Integer id;
/**
*
*/
private Integer userId;
/**
*
*/
private Integer movieId;
/**
*
*/
private String comment;
//註明不是該表字段
@TableField(exist = false)
private String userName;
@TableField(exist = false)
private String movieName;
setter and getter
xml文件
<mapper namespace="...dao.CommentDao">
<!-- 可根據自己的需求,是否要使用 -->
<resultMap type="...entity.CommentEntity" id="commentMap">
<result property="id" column="id"/>
<result property="userId" column="user_id"/>
<result property="movieId" column="movie_id"/>
<result property="comment" column="comment"/>
</resultMap>
<!-- 多表查詢,根據userid找到user表中的username-->
<select id="selectListPage" resultMap="commentMap">
select comment.id,comment.user_id,comment.movie_id,comment.comment,user.user_name as user_name,movie.movie_name as movie_name
from comment
left join user on user.id = comment.user_id
left join movie on movie.id = comment.movie_id
<!-- 使用該語句接收不同的參數查詢,這是mybatis-plus自帶的 -->
<where>
${ew.sqlSegment}
</where>
limit #{offset},#{size}
</select>
</mapper>
Dao層
@Mapper
public interface CommentDao extends BaseMapper<CommentEntity> {
List<CommentEntity> selectListPage(@Param("offset") long offset, @Param("size") long size, @Param("ew") Wrapper wrapper);
}
Service層
@Autowired
private CommentDao commentDao;
@Override
public PageUtils queryPage(Map<String, Object> params) {
//設置查詢條件
QueryWrapper<CommentEntity> wrapper = new QueryWrapper<CommentEntity>();
//關聯多表查詢,一次查詢完成,提高效率
IPage<CommentEntity> page = new Query<CommentEntity>().getPage(params);
page.setTotal(this.baseMapper.selectCount(wrapper));
page.setRecords(commentDao.selectListPage(page.offset(),page.getSize(),wrapper));
return new PageUtils(page);
}
注意事項:
在xml中的sql語句查出來的字段,java中的實體類需要有與之對應屬性,不然會報錯