Mybatis注解开发之批量添加和批量更新

    xiaoxiao2022-07-13  160

    前言

    大部分使用mybatis的开发者都是用xml配置文件来操作数据库。但是我们公司使用的是注解开发,xml文件方式官方有批量操作文档,但是注解方式官方没有提供任何批量操作的文档。所以,网上找了一下,然后自己试了试,记录一下。

    一、实体类

    先照着数据库写一个实体类吧

    public class ChatRecordDO implements Serializable { private static final long serialVersionUID = 1L; /** 主键*/ private Long id; /** 发送者id*/ private String sendUserId; /** 接收者id*/ private String receiveUserId; /** 消息*/ private String msg; /** 时间*/ private LocalDateTime createTime; /** 签收标记 1:已读, 0:未读*/ private Integer signFlag; /** 是否删除 0:删除,1:正常*/ private Integer isDelete; public ChatRecordDO() { super(); } public ChatRecordDO(Long id, String sendUserId) { super(); this.id = id; this.sendUserId = sendUserId; } //省略setter和getter }

    二、数据库操作

    1、批量更新,注解方式是可以用provider来动态拼接SQL语句的,但是批量操作不太好拼接,provider里也没有foreach这个关键字,所以就还是参考XML里的方式来写SQL语句。

    @Update({"<script> UPDATE chat_record_table SET is_delete = #{isDelete} " + "WHERE id IN " + "<foreach collection = 'ids' item = 'id' index = 'index' open = '(' separator= ',' close = ')' >" + " #{id} " + "</foreach>" + "</script>"}) Integer batchUpdateById(@Param("isDelete")Integer isDelete,@Param("ids")List<Long> ids)throws Exception;

    2、批量添加

    @Insert("<script> INSERT INTO chat_record_table " + "(id,send_user_id) " + "VALUES " + "<foreach collection = 'list' item='record' separator=',' > " + " (#{record.id},#{record.sendUserId}) " + "</foreach>" + "</script>") Integer batchInsert(List<ChatRecordDO> list)throws Exception;

    三、使用

    然后写个测试类测试一下就可以了。没啥问题,以后使用的话,参考着来写就可以了。

    @RunWith(SpringRunner.class) @SpringBootTest public class PatchSqlApplicationTests { @Autowired private ChatRecordLWQDAO recordDAO; @Test public void testUpdate() throws Exception{ List<Long> idList = new ArrayList<Long>(); idList.add(1131138401882476544L); idList.add(1131138401882476545L); recordDAO.batchUpdateById(0, idList); } @Test public void testInsert() throws Exception{ List<ChatRecordDO> list = new ArrayList<ChatRecordDO>(); list.add(new ChatRecordDO(1131138401882476547L,"123")); list.add(new ChatRecordDO(1131138401882476548L,"123")); recordDAO.batchInsert(list); } }

     

    最新回复(0)