动态SQL的sql标签和foreach标签


sql标签


    
        
            title=#{title},
        
        
            author=#{author},
        
    
 
    
        update blog
        
            
        
        where views=#{views}
    

注意:使用sql片段主要是为了实现sql片段的复用,如果sql语句涉及到了多表查询,就不建议使用sql片段。总的来说,sql片段适用于单表查询

foreach标签

编写接口

 //使用foreach查询
    List getBlogForeach(Map map);

编写Mapper文件

 

实现

 public void getBlogForeach(){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();
        blogMapper mapper = sqlSession.getMapper(blogMapper.class);
        HashMap map = new HashMap();
        ArrayList ids = new ArrayList();
        ids.add(1);
        ids.add(2);
        map.put("ids",ids);
        List 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.