Mybatis-Flex之增、删、改
方法全解
(1) INSERT
BaseMapper 的接口提供了 insert 和 insertBatch 方法,用于新增数据;
- insert(entity):插入实体类数据,不忽略 null 值。
- insertSelective(entity):插入实体类数据,但是忽略 null 的数据,只对有值的内容进行插入。这样的好处是数据库已经配置了一些默认值,这些默认值才会生效。
- insert(entity, ignoreNulls):插入实体类数据。
- insertWithPk(entity):插入带有主键的实体类,不忽略 null 值。
- insertSelectiveWithPk(entity):插入带有主键的实体类,忽略 null 值。
- insertWithPk(entity, ignoreNulls):带有主键的插入,此时实体类不会经过主键生成器生成主键。
- insertBatch(entities):批量插入实体类数据,只会根据第一条数据来构建插入的字段内容。
- insertBatch(entities, size):批量插入实体类数据,按 size 切分。
- insertOrUpdate(entity):插入或者更新,若主键有值,则更新,若没有主键值,则插入,插入或者更新都不会忽略 null 值。
- insertOrUpdateSelective(entity):插入或者更新,若主键有值,则更新,若没有主键值,则插入,插入或者更新都会忽略 null 值。
- insertOrUpdate(entity, ignoreNulls):插入或者更新,若主键有值,则更新,若没有主键值,则插入。
① insert
/**
* insert(entity):插入实体类数据,不忽略 null 值。
* insert(entity, ignoreNulls):插入实体类数据。
*/
@Test
public void testInsert() {
/**
* 默认不忽略null值
* INSERT INTO `tb_account`(`user_name`, `age`, `birthday`) VALUES (?, ?, ?)
*/
int row = accountMapper.insert(new Account().setUserName(null).setBirthday(new Date()).setAge(25));
Assertions.assertEquals(row, 1);
/**
* ignoreNulls true:忽略null , false:不忽略null
* INSERT INTO `tb_account`(`user_name`) VALUES (?)
*/
int row2 = accountMapper.insert(new Account().setUserName("ly3").setBirthday(null).setAge(null), true);
Assertions.assertEquals(row2, 1);
}
② insertSelective
/**
* insertSelective(entity):插入实体类数据,但是忽略 null 的数据,只对有值的内容进行插入。这样的好处是数据库已经配置了一些默认值,这些默认值才会生效。
*/
@Test
public void testInsertSelective() {
/**
* INSERT INTO `tb_account`(`user_name`) VALUES (?)
*/
int row = accountMapper.insertSelective(new Account().setUserName("陈远航").setAge(null));
Assertions.assertEquals(row, 1);
}
③ insertWithPk
/**
* insertWithPk(entity):插入带有主键的实体类,不忽略 null 值。
*/
@Test
public void testInsertWithPk() {
/**
* INSERT INTO `tb_account`(`id`, `user_name`, `age`, `birthday`) VALUES (?, ?, ?, ?)
*/
int row = accountMapper.insertWithPk(new Account().setUserName("廖楷瑞").setId(5L).setBirthday(null));
Assertions.assertEquals(row, 1);
}
④ insertBatch
/**
* insertBatch(entities):批量插入实体类数据,只会根据第一条数据来构建插入的字段内容。
* insertBatch(entities, size):批量插入实体类数据,按 size 切分。
*/
@Test
public void testInsertBatch() {
List<Account> accounts = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
Account account = new Account().setUserName("ly" + i).setBirthday(new Date()).setAge(20 + i);
accounts.add(account);
}
/**
* 批量插入,可以指定每次插入的数据大小size
* size=2 : INSERT INTO `tb_account`(`user_name`, `age`, `birthday`) VALUES (?, ?, ?), (?, ?, ?)
* size=3 : INSERT INTO `tb_account`(`user_name`, `age`, `birthday`) VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?)
* ......
*/
int rows = accountMapper.insertBatch(accounts, 2);
System.out.println("rows = " + rows);
}
⑤ insertOrUpdate
/**
* insertOrUpdate(entity):插入或者更新,若主键有值,则更新,若没有主键值,则插入,插入或者更新都不会忽略 null 值。
* insertOrUpdateSelective(entity):插入或者更新,若主键有值,则更新,若没有主键值,则插入,插入或者更新都会忽略 null 值。
* insertOrUpdate(entity, ignoreNulls):插入或者更新,若主键有值,则更新,若没有主键值,则插入。
*/
@Test
public void testInsertOrUpdate() {
Account account = new Account().setUserName("ly-update2").setId(3L).setBirthday(new Date()).setAge(21);
/**
* UPDATE `tb_account` SET `user_name` = ? , `age` = ? , `birthday` = ? WHERE `id` = ?
*/
int row = accountMapper.insertOrUpdate(account);
Assertions.assertEquals(row, 0, 1);
account = new Account().setUserName("ly-update2").setBirthday(null).setAge(21);
/**
* INSERT INTO `tb_account`(`user_name`, `age`) VALUES (?, ?)
*/
int row2 = accountMapper.insertOrUpdateSelective(account);
Assertions.assertEquals(row2, 0, 1);
}
(2) DELETE
BaseMapper 的接口提供了 deleteById、deleteBatchByIds、deleteByMap、deleteByQuery 方法,用于删除数据;
- deleteById(id):根据主键删除数据。如果是多个主键的情况下,需要传入数组,例如:new Integer[]{100,101}。
- deleteBatchByIds(ids):根据多个主键批量删除数据。
- deleteBatchByIds(ids, size):根据多个主键批量删除数据。
- deleteByMap(whereConditions):根据 Map 构建的条件来删除数据。
- deleteByCondition(whereConditions):根据查询条件来删除数据。
- deleteByQuery(queryWrapper):根据查询条件来删除数据。
① deleteById
/**
* deleteById(id):根据主键删除数据。
* ??? 如果是多个主键的情况下,需要传入数组,例如:new Integer[]{100,101}。 ??? 怀疑态度
*/
@Test
public void testDeleteById() {
/**
* DELETE FROM `tb_account` WHERE `id` = ?
*/
int row = accountMapper.deleteById(9L);
Assertions.assertTrue(row > 0);
}
② deleteBatchByIds
/**
* deleteBatchByIds(ids):根据多个主键批量删除数据。
* deleteBatchByIds(ids, size):根据多个主键批量删除数据。
*/
@Test
public void testDeleteBatchByIds() {
List<Integer> ids = List.of(5, 6, 7, 8);
/**
* DELETE FROM `tb_account` WHERE `id` = ? OR `id` = ? OR `id` = ? OR `id` = ?
*/
int rows = accountMapper.deleteBatchByIds(ids);
Assertions.assertTrue(rows > 0);
/**
* 分批删除
* size=2 : DELETE FROM `tb_account` WHERE `id` = ? OR `id` = ?
*/
int rows2 = accountMapper.deleteBatchByIds(ids, 2);
Assertions.assertTrue(rows2 > 0);
}
③ deleteByMap
/**
* deleteByMap(whereConditions):根据 Map 构建的条件来删除数据。
*/
@Test
public void testDeleteByMap() {
/**
* DELETE FROM `tb_account` WHERE `tb_account`.`age` = ?
*/
int rows = accountMapper.deleteByMap(Map.of("age", 25));
Assertions.assertTrue(rows > 0);
}
④ deleteByCondition
/**
* deleteByCondition(whereConditions):根据查询条件来删除数据。
*/
@Test
public void testDeleteByCondition() {
QueryCondition condition = QueryCondition.createEmpty().and("age = 27");
/**
* DELETE FROM `tb_account` WHERE age = 27
*/
int rows = accountMapper.deleteByCondition(condition);
Assertions.assertTrue(rows > 0);
/**
* DELETE FROM `tb_account` WHERE `id` > ?
*/
int rows2 = accountMapper.deleteByCondition(ACCOUNT.ID.gt(35));
Assertions.assertTrue(rows2 > 0);
}
⑤ deleteByQuery
/**
* deleteByQuery(queryWrapper):根据查询条件来删除数据。
*/
@Test
public void testDeleteByQuery() {
/**
* DELETE FROM `tb_account` WHERE `age` >= ?
*/
QueryWrapper wrapper = QueryWrapper.create().where(ACCOUNT.AGE.ge(32));
int rows = accountMapper.deleteByQuery(wrapper);
Assertions.assertTrue(rows > 0);
}
(3) UPDATE
BaseMapper 的接口提供了 update、updateByMap、updateByQuery 方法,用于更新数据;
- update(entity):根据主键来更新数据,若实体类属性数据为 null,该属性不会新到数据库。
- update(entity, ignoreNulls):根据主键来更新数据到数据库。
- updateByMap(entity, whereConditions):根据 Map 构建的条件来更新数据。
- updateByMap(entity, ignoreNulls, whereConditions):根据 Map 构建的条件来更新数据。
- updateByCondition(entity, whereConditions):根据查询条件来更新数据。
- updateByCondition(entity, ignoreNulls, whereConditions):根据查询条件来更新数据。
- updateByQuery(entity, queryWrapper):根据查询条件来更新数据。
- updateByQuery(entity, ignoreNulls, queryWrapper):根据查询条件来更新数据。
① update
@Test
public void testUpdate() {
Account account = new Account().setId(5L)
.setAge(39)
.setUserName("测试修改")
.setBirthday(new Date(2023, Calendar.SEPTEMBER, 6, 12, 12, 12));
/**
* UPDATE `tb_account` SET `user_name` = ? , `age` = ? , `birthday` = ? WHERE `id` = ?
*/
int rows = accountMapper.update(account);
Assertions.assertTrue(rows > 0);
}
@Test
public void testUpdateIgnoreNulls() {
Account account = new Account().setId(6L)
.setAge(null)
.setUserName(null)
.setBirthday(new Date(2023, Calendar.SEPTEMBER, 6, 12, 12, 12));
/**
* 不忽略null值
* UPDATE `tb_account` SET `user_name` = ? , `age` = ? , `birthday` = ? WHERE `id` = ?
*/
int rows = accountMapper.update(account, false);
System.out.println("rows = " + rows);
}
② updateByMap
@Test
public void testUpdateByMap() {
Account account = new Account()
.setId(7L) // 不生效
.setUserName("updateByMap")
.setAge(24)
.setBirthday(null);
// 注意:这样更新实体类的id是不生效的
Map<String, Object> whereCondition = Map.of("id", 13);
/**
* 忽略null
* UPDATE `tb_account` SET `user_name` = ? , `age` = ? WHERE `id` = ?
*/
accountMapper.updateByMap(account, whereCondition);
/**
* 不忽略null
* UPDATE `tb_account` SET `user_name` = ? , `age` = ? , `birthday` = ? WHERE `id` = ?
*/
accountMapper.updateByMap(account, false, whereCondition);
}
③ updateByCondition
/**
* updateByCondition(entity, whereConditions):根据查询条件来更新数据。
* updateByCondition(entity, ignoreNulls, whereConditions):根据查询条件来更新数据。
*/
@Test
public void testUpdateByCondition() {
Account account = new Account()
.setId(8L)
.setUserName("updateByCondition")
.setBirthday(DateUtil.toDate(LocalDateTime.now()));
QueryCondition condition = QueryCondition.create(new QueryColumn("id"),
SqlConsts.EQUALS, 8);
/**
* 忽略null
* UPDATE `tb_account` SET `user_name` = ? , `birthday` = ? WHERE `id` = ?
*/
accountMapper.updateByCondition(account, condition);
/**
* 不忽略null
* UPDATE `tb_account` SET `user_name` = ? , `age` = ? , `birthday` = ? WHERE `id` = ?
*/
accountMapper.updateByCondition(account, false, condition);
}
④ updateByQuery
/**
* updateByQuery(entity, queryWrapper):根据查询条件来更新数据。
* updateByQuery(entity, ignoreNulls, queryWrapper):根据查询条件来更新数据。
*/
@Test
public void testUpdateByQuery() {
Account account = new Account().setUserName("updateByQuery");
/**
* UPDATE `tb_account` SET `user_name` = ? WHERE `id` = ?
*/
accountMapper.updateByQuery(account,
QueryWrapper.create().where(ACCOUNT.ID.eq(9L)));
}
⑤ UpdateEntity部分字段更新
@Test
public void testUpdateEntity1() {
Account account = UpdateEntity.of(Account.class, 10L);
/**
* 官方说明:通过 UpdateEntity 创建的对象,只会更新调用了 setter 方法的字段,若不调用 setter 方法,不管这个对象里的属性的值是什么,都不会更新到数据库。
*/
account.setAge(66)
.setUserName("UpdateEntity")
.setBirthday(null);
accountMapper.update(account);
}
@Test
public void testUpdateEntity2() {
Account account = new Account()
.setId(10L)
.setUserName("UpdateEntity2");
UpdateWrapper wrapper = UpdateWrapper.of(account);
// wrapper.set(ACCOUNT.AGE, ACCOUNT.AGE.add(1));
wrapper.setRaw("age", "age + 1");
accountMapper.update(account);
}
@Test
public void testUpdateEntity3() {
Account account = new Account()
.setId(10L)
.setUserName("UpdateEntity2");
UpdateWrapper wrapper = UpdateWrapper.of(account);
// wrapper.set(ACCOUNT.AGE, ACCOUNT.AGE.add(1));
wrapper.setRaw(ACCOUNT.AGE, "select * from t_account where id = 3");
// accountMapper.updateByCondition(account, wrapper);
}
⑥ UpdateChain
@Test
public void testUpdateChain() {
/**
* UPDATE `tb_account` SET `birthday` = ? , `age` = age + 1 WHERE `age` = ?
*/
UpdateChain.of(Account.class)
.set(Account::getBirthday, new Date())
.setRaw(Account::getAge, "age + 1")
.where(ACCOUNT.AGE.eq(11)).update();
}
set() 和 setRaw() 的区别
在 Row、UpdateWrapper、UpdateChain 中,都提供了 set() 和 setRaw() 两个方法用于设置数据。 那么,他们有什么区别呢?
- set() 方法用于设置参数数据。
- setRaw() 用于设置 SQL 拼接数据。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构