Mybatis注解开发之批量添加和批量更新
前⾔
⼤部分使⽤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批量更新sql语句
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);
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。