Mybatis 系列6-动态SQL
if标签
<if>
的test属性写对象属性名,且连接符号使用sql中的语句,比如使用and而不是&&
<select id="findUserByCondition" resultType="com.mantishell.domain.User" parameterType="com.mantishell.domain.User">
select * from user where 1=1
<if test="name!=null">
and name = #{name}
</if>
<if test="sex!=null">
and sex=#{sex}
</if>
</select>
接口:
List<User> findUserByCondition(User user);
测试:
@Test
public void testFindByCondition(){
User user = new User();
user.setName("李四");
user.setSex("男");
List<User> users = userDao.findUserByCondition(user);
for (User u : users) {
System.out.println(u);
}
}
where标签
如果不写where 1=1的条件拼接,有没有办法呢?答案是肯定的,使用<where>
标签
<!--实现和where 1=1 拼接一样的效果-->
<select id="findUserByCondition" resultType="com.mantishell.domain.User" parameterType="com.mantishell.domain.User">
select * from user
<where>
<if test="name!=null">
and name=#{name}
</if>
<if test="sex!=null">
and sex=#{sex}
</if>
</where>
</select>
如果name和sex参数都不为null
sql语句相当于:select * from user where 1=1 and name='xx' and sex='xx'
foreach标签
<foreach>
标签用于遍历
属性:
collection:代表要遍历的集合元素,注意不要写#{},写pojo中的属性名
open:语句的开始部分
close:结束部分
item:遍历集合的每个元素,生成的变量名,只需要和#{}里的名称相同,名字可以随便取
sperator:分隔符
比如sql语句:
select * from user where id in (1,3,5,6,7)
那么xml里该怎么写呢?
<select id="findUserInIds" resultType="com.mantishell.domain.User" parameterType="com.mantishell.domain.QueryVo">
select * from user
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in(" close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
接口:
List<User> findUserInIds(QueryVo vo);
QueryVo jojo:
package com.mantishell.domain;
import java.util.List;
public class QueryVo {
private User user;
private List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
测试:
@Test
public void testFindInIds(){
QueryVo vo = new QueryVo();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(5);
vo.setIds(list);
List<User> users = userDao.findUserInIds(vo);
for (User user : users) {
System.out.println(user);
}
}
==> Preparing: select * from user WHERE id in( ? , ? , ? )
==> Parameters: 1(Integer), 3(Integer), 5(Integer)
Sql片段
发现每次查询都要写:select * from user
<sql>
标签可以将其提取出来,然后在使用的时候使用<include>
替换原来的sql语句即可
<!--抽取重复的语句代码片段-->
<sql id="defaultsql">
select * from user
</sql>
<select id="findAll" resultType="com.mantishell.domain.User">
<include refid="defaultsql"></include>
</select>
<select id="findUserById" parameterType="int" resultType="com.mantishell.domain.User">
<include refid="defaultsql"></include>
where id=#{userid}
</select>