MyBatis常用知识点汇聚

1、查询条件

<!-- 查询条件SQL(动态生成) -->
<sql id="condition_sql">
	<if test="id != null and id != ''"> and ID = #{id}</if>
	<if test="fieldName != null and fieldName != ''"> and FIELD_NAME like CONCAT(CONCAT('%',#{fieldName}), '%') </if>
	<if test="beginDate!=null and beginDate!=''">
	<![CDATA[ and DATE_FORMAT(CREATE_TIME, '%Y-%m-%d') >=  DATE_FORMAT(#{beginDate}, '%Y-%m-%d') ]]>
	</if>
	<if test="endDate!=null and endDate!=''">
	<![CDATA[ and DATE_FORMAT(CREATE_TIME, '%Y-%m-%d') <=  DATE_FORMAT(#{endDate}, '%Y-%m-%d') ]]>
	</if>
</sql

 2、String字符串参数 返回列表

<select id="xxx" parameterType="java.lang.String" resultMap="BaseResultMap">
	select
	<include refid="Base_Column_List" />
	from XXX where code = #{0}  
</select>

 3、String字符串参数,返回列表

<select id="selectByName" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from tb_xxx
    where name = #{name,jdbcType=VARCHAR}
</select>

 4、参数传列表 sql用in

JAVA:

List<Integer> list = new ArrayList<String>();
Map<String, Object> paramMap = new HashMap<String, Object>();	
param.put("list", list);
Pager<XxxDto> page = this.xxxService.queryByXxx(param, 0, 1000);

 XML:

<choose>
<when test="list != null and list['size'] &gt; 0">
	and xxx in 
	<foreach close=")" collection="list" item="item" open="(" separator=",">
		#{item,jdbcType=TINYINT}
	</foreach>
</when>
<otherwise>
	and 1=2
</otherwise>
</choose>

http://www.mybatis.org/mybatis-3/zh/dynamic-sql.html

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’ 
  <if test="title != null">
    AND title like #{title}
  </if>
  <if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>
</select>

猜你喜欢

转载自19965345.iteye.com/blog/2323976