6.动态sql - if

满足条件的数据
mapper.xml 满足if条件就执行,不满足就不加
<select id="selectStateByTitle" parameterType="string" resultMap="blogResultMap">
select * from blog
where state = "1"
<if test="value != null and value != ''">
and title like '%${value}%'
</if>
 
</select>
接口:mapper
List<Blog> selectStateByTitle(String title);
测试 test 可以写满足的条件也可以不写
@Test
public void testSelectStateByTitle(){
SqlSession session = MybatisUtil.getSqlSession();
BlogMapper blogMapper = session.getMapper(BlogMapper.class);
List<Blog> blogList = blogMapper.selectStateByTitle(null);
session.close();
 
System.out.println("<<<<<------ 查询------>>>>>:"+blogList);
}
 
实际应用在代码中
 1 <select id="findList" resultType="Periodical">
 2         SELECT 
 3             <include refid="periodicalColumns"/>
 4         FROM periodical a
 5         <include refid="periodicalJoins"/>
 6         <where>
 7             a.del_flag = #{DEL_FLAG_NORMAL}
 8             <if test="type != null and type != ''">
 9                 AND  type = #{type}
10             </if>
11             <if test="name != null and name != ''">
12                 AND a.name LIKE 
13                     <if test="dbName == 'oracle'">'%'||#{name}||'%'</if>
14                     <if test="dbName == 'mssql'">'%'+#{name}+'%'</if>
15                     <if test="dbName == 'mysql'">concat('%',#{name},'%')</if>
16             </if>
17         </where>
18         <choose>
19             <when test="page !=null and page.orderBy != null and page.orderBy != ''">
20                 ORDER BY ${page.orderBy}
21             </when>
22             <otherwise>
23                 ORDER BY a.update_date DESC
24             </otherwise>
25         </choose>
26     </select>
27     

猜你喜欢

转载自www.cnblogs.com/zhukaixin/p/9155953.html
今日推荐