1. 程式人生 > >mybatis @Select註解中如何拼寫動態sql

mybatis @Select註解中如何拼寫動態sql

package cn.erongcai.hrplatform.dao.demand;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.baomidou.mybatisplus.mapper.BaseMapper;

import cn.erongcai.hrplatform.model.demand.DemandComment;

@Mapper
public interface DemandCommentMapper extends BaseMapper<DemandComment>{
	
	@Select("SELECT "
			+ "a.id as 'id',a.create_date as 'createDate',a.content as 'content',"
			+ "a.parent_id as 'parentId',a.first_comment_id as 'firstCommentId',"
			+ "b.id as 'fromUser.id',b.realname as 'fromUser.realname',b.avatar as 'fromUser.avatar',"
			+ "c.id as 'toUser.id',c.realname as 'toUser.realname',c.avatar as 'toUser.avatar' "
			+ "FROM t_demand_comment a "
			+ "LEFT JOIN t_user b ON b.id = a.from_uid "
			+ "LEFT JOIN t_user c ON c.id = a.to_uid "
			+ "WHERE a.demand_id = #{demandId} "
			+ "ORDER BY a.create_date ASC"
			+ "LIMIT #{startNo},#{pageSize}")
	public List<DemandComment> listDemandComment(@Param("demandId") Long demandId, @Param("startNo") Integer pageNo, @Param("pageSize") Integer pageSize);
}

這樣整個語句是寫死的,如果我想根據pageNo與pageSize是否為空來判斷是否需要分頁,該怎麼做呢?

如果使用xml來配置的話可以用

<when test='startNo!=null and pageSize != null '>
  LIMIT #{startNo},#{pageSize}
</when>
如果是用@Select 這種該如何做呢?

方法:用script標籤包圍,然後像xml語法一樣書寫

package cn.erongcai.hrplatform.dao.demand;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.baomidou.mybatisplus.mapper.BaseMapper;

import cn.erongcai.hrplatform.model.demand.DemandComment;

@Mapper
public interface DemandCommentMapper extends BaseMapper<DemandComment>{
	
	@Select("<script>"
			+ "SELECT "
			+ "a.id as 'id',a.create_date as 'createDate',a.content as 'content',"
			+ "a.parent_id as 'parentId',a.first_comment_id as 'firstCommentId',"
			+ "b.id as 'fromUser.id',b.realname as 'fromUser.realname',b.avatar as 'fromUser.avatar',"
			+ "c.id as 'toUser.id',c.realname as 'toUser.realname',c.avatar as 'toUser.avatar' "
			+ "FROM t_demand_comment a "
			+ "LEFT JOIN t_user b ON b.id = a.from_uid "
			+ "LEFT JOIN t_user c ON c.id = a.to_uid "
			+ "WHERE a.demand_id = #{demandId} "
			+ "ORDER BY a.create_date ASC "
			+ "<if test='startNo!=null and pageSize != null '>"
			+ "LIMIT #{startNo},#{pageSize}"
			+ "</if>"
			+ "</script>")
	public List<DemandComment> listDemandComment(@Param("demandId") Long demandId, @Param("startNo") Integer pageNo, @Param("pageSize") Integer pageSize);
}