动态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.
posted @   小罗要有出息  阅读(59)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示