动态SQL
Mybatis动态SQL几种元素:
if 判断语句
chose(when,otherwise) 相当于Java中的switch和case
trim(where,set) 辅助元素,用于处理特定的SQL拼接问题,比如去掉多余的and、or等
foreach 循环语句 在in语句等列表条件常用
If使用:
映射文件:
<select id="findUser" parameterType="string" resultMap="userMapper">
select * from user where id=3
<if test="name != null and name != ''">
and name like concat ('%',#{name},'%')
</if>
</select>
查询user表,当传入参数为null或是‘’时,默认id=3查询user,否则,按传入的参数进行name的模糊查询。
接口:
public User findUser(@Param(value = "name") String username);
Main:
//User user = userMapper.findUser("");
//User user = userMapper.findUser("cy");
chose、when、otherwise元素使用:
<select id="findUser" parameterType="pojo.User" resultMap="userMapper">
select * from user where 1=1
<choose>
<when test="id != null and id != ''">
AND id = #{id}
</when>
<when test="name != null and name != ''">
AND name = #{name}
</when>
<otherwise>
AND age is not null
</otherwise>
</choose>
</select>
多条件进行查询
tirm、where、set元素:
Where使用:
<select id="findUser" parameterType="map" resultMap="userMapper">
select * from user
<where>
<if test="name != null and name != ''">
and name like concat ('%',#{name},'%')
</if>
<if test="age != null and age != 0">
and age = #{age}
</if>
</where>
</select>
接口:
public User findUser(Map<String,Object> parameterMap);
main:
Map<String,Object> p =new HashMap<String, Object>();
p.put("name","cy");
p.put("age",32);
User user1 = userMapper.findUser(p);
Trim使用:
trim用在要去掉一些特殊的字符串,