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,commentment,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中的实体类需要有与之对应属性,不然会报错

更多推荐

MyBatis-plus自己写sql语句