动态SQL的sql标签和foreach标签

2022/1/30 19:06:33

本文主要是介绍动态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.


这篇关于动态SQL的sql标签和foreach标签的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程