Mybatis三 | 动态SQL

目录

if

where

set

 foreach

 sql&include


ctrl + alt + l格式化SQL语句

 随着用户的输入或外部条件的变化而变化的SQL称为动态SQL

if

<if>用来判断条件是否成立,使用test属性进行条件判断,如果true,则拼接SQL 

where

wehre元素只会在有条件成立的情况下才插入where子句,而且会自动去除开头的AND或OR

如果存在只传递姓名的情况,之前的程序会无法成功查询,可以通过动态SQL解决上述问题 

EmpMapper.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.EmpMapper">
    <select id="list" resultType="com.itheima.pojo.Emp">
        select *
        from emp
        <where>
            <if test="name != null">
              name like concat('%', #{name}, '%')
            </if>
          <if test="gender != null">
              and gender = #{gender}
          </if>
          <if test="begin != null and end != null">
              and entrydate between #{begin} and #{end}
          </if>
        </where>
        order by update_time desc
    </select>
</mapper>

 SpringbootMybatisCrudApplicationTests.java

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;

    @Test
    public void testSelect(){
        List<Emp> list = empMapper.list(null,(short)1,null,null);
        System.out.println(list);
    }

}

 运行结果如下 

set

<set>动态地在行首插入SET关键字,并会删掉额外的逗号(用在update语句中) 

将id为18的员工的username改为Tom111,name改为Tom111,gender改为2,其他不变

按照之前的方法进行更新会使其他值均变为null

可以通过动态SQL解决

EmpMapper.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.EmpMapper">
    <update id="update">
        update emp
        <set>
            <if test="username != null">username=#{username},</if>
            <if test="password != null">password=#{password},</if>
            <if test="name != null">name=#{name},</if>
            <if test="gender != null">gender=#{gender},</if>
            <if test="image != null">image=#{image},</if>
            <if test="job != null">job=#{job},</if>
            <if test="entrydate != null">entrydate=#{entrydate},</if>
            <if test="deptId != null">dept_id=#{deptId},</if>
            <if test="updateTime != null">update_time=#{updateTime}</if>
        </set>
        where id=#{id}
    </update>
</mapper>

EmpMapper.java

@Mapper
public interface EmpMapper {
    public void update(Emp emp);

}

此次更新id为19的员工,SpringbootMybatisCrudApplicationTests.java

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;

    @Test
    public void testUpdate(){
        Emp emp = new Emp();
        emp.setId(19);
        emp.setUsername("Tom2222");
        emp.setName("Tom222");
        emp.setGender((short)1);
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);
    }

}

 运行结果如下,发现只更新了四个字段,其余字段不变

 foreach

实现批量删除

collection 集合名称

item 集合遍历出来的元素,项

separator 每一次遍历使用的分隔符

open 遍历开始前拼接的片段

close 遍历结束后拼接的片段

EmpMapper.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.EmpMapper">
    <delete id="deleteByIds">
        delete from emp where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>

</mapper>

 SpringbootMybatisCrudApplicationTests.java

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;

    @Test
    public void testDeleteByIds(){
        List<Integer> ids = Arrays.asList(13,14,15);
        empMapper.deleteByIds(ids);
    }

}

EmpMapper.java

@Mapper
public interface EmpMapper {
    public void deleteByIds(List<Integer> ids);

}

运行发现删除成功

 sql&include

sql 定义可重用的片段

include 通过属性refid ,指定包含的sql片段

EmpMapper.xml  

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.EmpMapper">
    <sql id="commonSelect">
        select id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime
        from emp
    </sql>
    <select id="list" resultType="com.itheima.pojo.Emp">
        <include refid="commonSelect"/>
        <where>
            <if test="name != null">
                name like concat('%', #{name}, '%')
            </if>
            <if test="gender != null">
                and gender = #{gender}
            </if>
            <if test="begin != null and end != null">
                and entrydate between #{begin} and #{end}
            </if>
        </where>
        order by update_time desc
    </select>
</mapper>

  • 15
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
mybatis批量更新动态sql可以使用foreach标签来实现。在动态sql中,可以使用foreach标签来遍历一个集合,并对集合中的每个元素执行相同的sql语句。具体操作步骤如下: 1. 定义一个集合对象,用于存储要批量更新的数据。 2. 在mapper.xml文件中,使用<foreach>标签包裹要执行的sql语句。例如,对于Oracle 12C环境下的批量入库方式,可以按照以下格式编写sql语句: <insert id="insertSysUserLoanGroups" useGeneratedKeys="false"> insert into SYS_USER_LOAN_GROUP (USER_ID,GROUP_ID) ( <foreach item="item" index="index" collection="list" separator="UNION ALL"> select #{item.userId}, #{item.groupId} from dual </foreach> ) </insert> 在上述示例中,<foreach>标签中的collection属性指定了要遍历的集合对象,item属性指定了集合中的每个元素的别名,index属性指定了循环的索引变量名,separator属性指定了每个循环体之间的分隔符。 这样,通过foreach标签,可以将集合中的每个元素转换为一条insert语句的一部分,从而实现批量插入的功能。 3. 在Java代码中,使用mybatisSqlSession对象执行上述定义的批量更新操作。 通过调用SqlSession对象的insert方法,并指定要执行的sql语句的id(即insertSysUserLoanGroups),以及要传递给sql语句的参数,即定义的集合对象。 例如,可以按照以下方式执行批量更新操作: ``` List<UserLoanGroup> dataList = new ArrayList<>(); // 向dataList中添加要批量插入的数据 sqlSession.insert("insertSysUserLoanGroups", dataList); ``` 在上述示例中,insertSysUserLoanGroups是mapper.xml文件中定义的要执行的sql语句的id,dataList是要传递给sql语句的参数。 这样,就可以通过mybatis的foreach标签和SqlSession对象来实现mybatis批量更新动态sql的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「已注销」

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值