动态SQL的sql标签和foreach标签
作者:互联网
sql标签
<!--sql片段-->
<sql id="updateSql">
<if test="title != null">
title=#{title},
</if>
<if test="author != null">
author=#{author},
</if>
</sql>
<!--使用include引用sql片段-->
<update id="updateBlog" parameterType="map">
update blog
<set>
<include refid="updateSql"></include>
</set>
where views=#{views}
</update>
注意:使用sql片段主要是为了实现sql片段的复用,如果sql语句涉及到了多表查询,就不建议使用sql片段。总的来说,sql片段适用于单表查询
foreach标签
编写接口
//使用foreach查询
List<blog> getBlogForeach(Map map);
编写Mapper文件
<select id="getBlogForeach" resultType="blog" parameterType="map">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
实现
public void getBlogForeach(){
SqlSession sqlSession = sqlSessionFactory.getsqlSession();
blogMapper mapper = sqlSession.getMapper(blogMapper.class);
HashMap map = new HashMap();
ArrayList ids = new ArrayList<Object>();
ids.add(1);
ids.add(2);
map.put("ids",ids);
List<blog> blogs = mapper.getBlogForeach(map);
for (blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
运行结果
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 418958713.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@18f8cd79]
==> Preparing: select * from blog WHERE ( id=? or id=? )
==> Parameters: 1(Integer), 2(Integer)
<== Columns: id, title, author, create_time, views
<== Row: 1, Mybatis, 小落, 2022-01-26 15:45:58.0, 9999
<== Row: 2, 微服务11, 小落11, 2022-01-26 15:45:58.0, 1000
<== Total: 2
blog(id=1, title=Mybatis, author=小落, createTime=Wed Jan 26 15:45:58 CST 2022, views=9999)
blog(id=2, title=微服务11, author=小落11, createTime=Wed Jan 26 15:45:58 CST 2022, views=1000)
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@18f8cd79]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@18f8cd79]
Returned connection 418958713 to pool.
标签:connections,标签,ids,forcefully,blog,foreach,sql,id 来源: https://www.cnblogs.com/luoking/p/15856640.html