sql标签
| |
| <sql id="updateSql"> |
| <if test="title != null"> |
| title=#{title}, |
| </if> |
| <if test="author != null"> |
| author=#{author}, |
| </if> |
| </sql> |
| |
| <update id="updateBlog" parameterType="map"> |
| update blog |
| <set> |
| <include refid="updateSql"></include> |
| </set> |
| where views=#{views} |
| </update> |
注意:使用sql片段主要是为了实现sql片段的复用,如果sql语句涉及到了多表查询,就不建议使用sql片段。总的来说,sql片段适用于单表查询
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. |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?