4.where标签
修改上一条的SQL语句即可:
<select id="queryBolgIf" parameterType="map" resultType="cn.bobo.BolgDao.Bolg"> select * from blog <where> <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </where> </select>
5.Set标签
在至少有一个子元素返回了SQL语句时,才会向SQL语句中添加SET,并且如果SET之后是以,开头的话,会自动将其删掉
常用在修改的标签中
SQL语句:
<update id="updateBolg" parameterType="map"> update blog <set> <if test="title != null"> title = #{title}, </if> <if test="author != null"> author = #{author} </if> </set> where id = #{id}; </update>
测试类:
@Test public void testUpdateBlog(){ HashMap<String, String> map = new HashMap<String, String>(); map.put("title","在山里"); map.put("author","雪豹"); map.put("id","3b972c22cbd74c8dbfaaf35b4fa732fb"); blogMapper.updateBolg(map); }
6.Choose标签
有时候用不到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用choose标签可以满足
接口:
List<Blog> queryBlogChoose(Map map);
SQL语句:
<select id="queryBlogChoose" parameterType="map" resultType="cn.bobo.BolgDao.Bolg"> select * from blog <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>
测试类:
@Test public void testQueryBlogChoose(){ HashMap<String, Object> map = new HashMap<String, Object>(); map.put("title","Java如此简单"); map.put("author","狂神说"); map.put("views",9999); List<Bolg> bolgs = mapper.queryBolgChoose(map); System.out.println(blogs); }
7.SQL片段
有时候可以通过将部分代码抽出来作为公用,使用时候可以直接调用
SQL片段;
<sql id="if-title-author"> <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </sql>
引用SQL片段
<select id="queryBolgIf" parameterType="map" resultType="cn.bobo.BolgDao.Bolg"> select * from blog <where> <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace --> <include refid="if-title-author"></include> <!-- 在这里还可以引用其他的 sql 片段 --> </where> </select>
注意:在sql片段中不要包括where
8.Foreach
接口:
List<Blog> queryBlogForeach(Map map);
编写SQL语句:
<select id="queryBlogForeach" parameterType="map" resultType="cn.bobo.BolgDao.Bolg"> select * from blog <where> <!-- collection:指定输入对象中的集合属性 item:每次遍历生成的对象 open:开始遍历时的拼接字符串 close:结束时拼接的字符串 separator:遍历对象之间需要拼接的字符串 select * from blog where 1=1 and (id=1 or id=2 or id=3) --> <foreach collection="ids" item="id" open="and (" close=")" separator="or"> id=#{id} </foreach> </where> </select>
测试类:
@Test public void testQueryBlogForeach(){ SqlSession session = MybatisUtils.getSession(); BlogMapper mapper = session.getMapper(BlogMapper.class); HashMap map = new HashMap(); List<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(2); ids.add(3); map.put("ids",ids); List<Blog> blogs = mapper.queryBlogForeach(map); System.out.println(blogs) }