Mybatis动态SQL
动态SQL根据不同条件生成不同语句,利用java语言实现各种条件查询,而且还简化一些操作,避免了一些错误的发生,比如sql数据拼接时一定要加空格,去掉列表最后一个列名的逗号
where用法:
语句用来替代sql里面的where,这个东西,可以防止出错,这个where标签在后面没有条件的时候会自动省略,同时还会去掉and 和 or 两个词,在第一个条件不成立,第二个条件成立的情况下,默认给第二个条件去掉and 或者or,同时有了where标签可以省去where 1 =1 这个条件 例如:
mapper中:
<where>
<if test="title != null">
title=#{title}
</if>
<if test="author !=null">
and author=#{author}
</if>
<if test="id !=null">
and id=#{id}
</if>
</where>
</select>
</mapper>
test中:
// map.put("title","Mybatis如此简单");
map.put("author","abc");
map.put("id","01fad696342148589df1abca8ac7a4aa");
//得到的sql语句如下:select * from mybatis.b1og WHERE author=? and id=? 此时没有title条件,第二个条件默认为成第一个,同时去掉了and
## set用法
与where用法有些类似,这一标签可以去掉",“常用在更新查询中,如果在第一个条件不成立,第二个条件成立的情况下,默认给第二个条件去掉”," 例如:
<update id="updatablog" parameterType="map">
update mybatis.b1og
<set>
<if test="title != null">
title=#{title},
</if>
<if test="author !=null">
author=#{author}
</if>
</set>
where id=#{id}
</update>
写到这里,其实花了我很长时间,是被自己蠢哭的,在写完语句后一直没有提交,没有commit,我一直以为是我数据库的问题,没有报错,执行成功,但是没有修改成功,尝试了很多次,单独把sql也写过没问题,就是失败在没有提交上,mybatis默认为事务需要手动提交,当然也可以在主配置文件中加自动提交,但是应该知道的是,除了查不用提交事务,增删改都需要提交事务,另外还有一低级错误是除了查需要返回list之外,其余的一般都返回int
public static SqlSession getSqlSession()
{
return sqlSessionFactory.openSession(true); //如果不设置参数或者参数为false就是手动提交事务,参数设置为true就是自动提交事务
}
choose ,when,otherwise用法
choose的用法相当于java里面的swith case的用法,这里记住,即使多个条件满足,sql语句只会写第一个满足条件的,别的条件不会写例如:
<select id="getBlogchoose" parameterType="map" resultType="blog"> select * from mybatis.b1og <where> <choose> <when test="title!=null"> title=#{title} </when> <when test="author!=null"> and author=#{author} </when> <otherwise> and views=#{views} </otherwise> </choose> </where> </select>
在这里三个条件都满足了,但是sql语句为:
!
此图可以看出,如果when满足条件,则不会写overwise的条件,如果没有when,满足,就用overwise的
sql,include用法
主要是对将sql语句抽取出来,复用的
注意:1.针对单表查询做的(数据比较简单)
<update id="updatablog" parameterType="map">
update mybatis.b1og
<set>
<include refid="if-title-author"></include>
</set>
where id=#{id}
</update>
<sql id="if-title-author">
<if test="title != null">
title=#{title},
</if>
<if test="author !=null">
author=#{author}
</if>
</sql>
foreach用法:
这种sql用在选择时候从几个当中选出合适的条件执行,(相当于一个选取元素)例如:
<select id="getBlogforeach" parameterType="map" resultType="blog">
select * from mybatis.b1og
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
//collection:全部元素
//item:单个元素
//open:开始地方
//close:结束的地方
//separator:分割符(可以为and,or,","等)
这个语句等价于:select * from b1og where 1=1 and (id=1 or id = 2 or id =3)
测试:
@Test
public void queryforeach(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
//ids.add(3);
map.put("ids",ids);
List<Blog> blog = mapper.getBlogforeach(map);
for (Blog blog1 : blog) {
System.out.println(blog1);
}
sqlSession.close();
}
}
动态sql就是拼接sql语句,我们只要保证sql正确性,才能保证查询成功
可以先把sql语句写出来,再转换成动态sql的形式