MyBatis-Plus
不仅有BaseMapper
接口提供给基本的CRUD
功能,还在Service
层提供了IService
接口,扩展了BaseMapper
的功能。
官方文档 传送门
下面,详细整理IService<T>
提供的能力。
增
插入一条记录
default boolean save(T entity) {
return SqlHelper.retBool(getBaseMapper().insert(entity));
}
例子:
@Test
public void testSave() {
UserEntity user = new UserEntity();
user.setId(7L);
user.setName("Mike");
user.setAge(32);
user.setEmail("test7@baomidou.com");
boolean ret = userService.save(user);
System.out.println(ret);
}
控制台打印出来的日志:
==> Preparing: INSERT INTO tb_user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 7(Long), Mike(String), 32(Integer), test7@baomidou.com(String)
<== Updates: 1
批量插入一批记录
@Transactional(rollbackFor = Exception.class)
default boolean saveBatch(Collection<T> entityList) {
return saveBatch(entityList, DEFAULT_BATCH_SIZE);
}
boolean saveBatch(Collection<T> entityList, int batchSize);
例子:
@Test
public void testSaveBatch() {
UserEntity user1 = new UserEntity();
user1.setId(7L);
user1.setName("Mike");
user1.setAge(32);
user1.setEmail("test7@baomidou.com");
UserEntity user2 = new UserEntity();
user2.setId(8L);
user2.setName("Tank");
user2.setAge(30);
user2.setEmail("test8@baomidou.com");
boolean ret = userService.saveBatch(Arrays.asList(user1, user2));
System.out.println(ret);
}
控制台打印出来的日志:
==> Preparing: INSERT INTO tb_user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 7(Long), Mike(String), 32(Integer), test7@baomidou.com(String)
==> Parameters: 8(Long), Tank(String), 30(Integer), test8@baomidou.com(String)
批量插入或更新记录
@Transactional(rollbackFor = Exception.class)
default boolean saveOrUpdateBatch(Collection<T> entityList) {
return saveOrUpdateBatch(entityList, DEFAULT_BATCH_SIZE);
}
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
根据主键ID判断是否存在,如果不存在则新增,如果存在则更新(更新不为
null
的属性)。
例子:
@Test
public void testSaveOrUpdateBatch() {
UserEntity user1 = new UserEntity();
user1.setId(9L);
user1.setName("Adele");
user1.setAge(28);
user1.setEmail("test9@baomidou.com");
UserEntity user2 = new UserEntity();
user2.setId(8L);
user2.setAge(29);
user2.setEmail("test8@baomidou.com");
boolean ret = userService.saveOrUpdateBatch(Arrays.asList(user1, user2));
System.out.println(ret);
}
控制台打印出来的日志:
==> Preparing: SELECT id,name,age,email FROM tb_user WHERE id=?
==> Parameters: 9(Long)
<== Total: 0
==> Preparing: INSERT INTO tb_user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 9(Long), Adele(String), 28(Integer), test9@baomidou.com(String)
==> Preparing: SELECT id,name,age,em