Mybatis——动态SQL(if标签、foreach标签、SQL片段抽取)

26 篇文章 0 订阅
8 篇文章 0 订阅
本文介绍了MyBatis中动态SQL的使用,包括if标签和foreach标签的示例。if标签用于根据传入参数动态添加查询条件,而foreach标签则用于处理列表参数,实现IN查询。同时,还展示了如何通过SQL片段来复用SQL语句,提高代码的可维护性。
摘要由CSDN通过智能技术生成

if标签

  • UserMapper.xml
<!--根据user进行查询,动态SQL if标签-->
    <!--当参数内有值时才作为查询条件-->
    <select id="findByUser" resultType="user" parameterType="user">
        select * from user
        <!--动态添加where关键字-->
        <where>
            <if test="id!=0">
                and id = #{id}
            </if>
            <if test="name!=null">
                and name = #{name}
            </if>
            <if test="password">
                and password = #{password}
            </if>
        </where>
    </select>
  • UserXmlMapper
@Mapper
@Repository
public interface UserXmlMapper {
    public List<User> findByUser(User user);
}
  • 测试代码
    @Test
    public void testFindByUser(){
        user.setId(1234567805);
        user.setName("老七");
        user.setPassWord("123456");
        List<User> list = userXmlMapper.findByUser(user);
        System.out.println(list);
    }

foreach标签

  • UserMapper.xml
<!--利用list装入多个id值进行查询,动态SQL foreach标签-->
    <select id="findByIds" parameterType="list" resultType="user">
        select * from user
        <where>
            <!--open是开始部分语句,close则是关闭部分语句,separator是分隔符-->
            <foreach collection="list" open="id in(" close=")" item="id" separator=",">
                #{id}
            </foreach>
        </where>
    </select>
  • UserXmlMapper
@Mapper
@Repository
public interface UserXmlMapper {
    public List<User> findByIds(List<Integer> ids);
}
  • 测试代码
    @Test
    public void testFindByIds(){
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(1234567801);
        ids.add(1234567802);
        ids.add(1234567803);
        List<User> list = userXmlMapper.findByIds(ids);
        System.out.println(list);
    }

SQL片段抽取

    <!--SQL语句的抽取-->
    <sql id="selectUser"> select * from user </sql>
    <!--查询操作-->
    <select id="findAll" resultType="user">
        <!--select * from user-->
        <include refid="selectUser"></include>
    </select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值