【第3章】MyBatis-Plus持久层接口之Service Interface(上)


前言

接下来详细介绍了 MyBatis-Plus 进行持久化操作的各种方法,包括插入、更新、删除、查询和分页等。通过本文,您可以了解到 MyBatis-Plus 提供的各种方法是如何进行数据操作的,以及它们对应的 SQL 语句。

本文介绍IService ,IService 是 MyBatis-Plus 提供的一个通用 Service 层接口,它封装了常见的 CRUD 操作,包括插入、删除、查询和分页等。通过继承 IService 接口,可以快速实现对数据库的基本操作,同时保持代码的简洁性和可维护性。

IService 接口中的方法命名遵循了一定的规范,如 get 用于查询单行,remove 用于删除,list 用于查询集合,page 用于分页查询,这样可以避免与 Mapper 层的方法混淆。

Service Interface:

  • save
  • saveOrUpdate
  • remove
  • update

一、save

// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);

功能描述: 插入记录,根据实体对象的字段进行策略性插入。
返回值: boolean,表示插入操作是否成功。
参数说明

类型参数名描述
Tentity实体对象
CollectionentityList实体对象集合
intbatchSize插入批次数量

1. 示例(save)

// 假设有一个 User 实体对象
User user = new User();
user.setName("John Doe");
user.setEmail("john.doe@example.com");
boolean result = userService.save(user); // 调用 save 方法
if (result) {
    System.out.println("User saved successfully.");
} else {
    System.out.println("Failed to save user.");
}

生成的 SQL:

INSERT INTO user (name, email) VALUES ('John Doe', 'john.doe@example.com')

2. 示例(saveBatch)

// 假设有一组 User 实体对象
List<User> users = Arrays.asList(
    new User("Alice", "alice@example.com"),
    new User("Bob", "bob@example.com"),
    new User("Charlie", "charlie@example.com")
);
// 使用默认批次大小进行批量插入
boolean result = userService.saveBatch(users); // 调用 saveBatch 方法,默认批次大小
if (result) {
    System.out.println("Users saved successfully.");
} else {
    System.out.println("Failed to save users.");
}

生成的 SQL(假设默认批次大小为 3):

INSERT INTO user (name, email) VALUES
('Alice', 'alice@example.com'),
('Bob', 'bob@example.com'),
('Charlie', 'charlie@example.com')

3. 示例(saveBatch 指定批次大小)

// 假设有一组 User 实体对象
List<User> users = Arrays.asList(
    new User("David", "david@example.com"),
    new User("Eve", "eve@example.com"),
    new User("Frank", "frank@example.com"),
    new User("Grace", "grace@example.com")
);
// 指定批次大小为 2进行批量插入
boolean result = userService.saveBatch(users, 2); // 调用 saveBatch 方法,指定批次大小
if (result) {
    System.out.println("Users saved successfully.");
} else {
    System.out.println("Failed to save users.");
}

生成的 SQL(指定批次大小为 2):

-- 第一批次
INSERT INTO user (name, email) VALUES
('David', 'david@example.com'),
('Eve', 'eve@example.com')

-- 第二批次
INSERT INTO user (name, email) VALUES
('Frank', 'frank@example.com'),
('Grace', 'grace@example.com')

通过上述示例,我们可以看到 save 系列方法是如何在 Service 层进行批量插入操作的,以及它们对应的 SQL 语句。这些方法大大简化了插入操作的代码编写,提高了开发效率。

二、saveOrUpdate

// TableId 注解属性值存在则更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);

功能描述 : 根据实体对象的主键 ID 进行判断,存在则更新记录,否则插入记录。
返回值: boolean,表示插入或更新操作是否成功。
参数说明

类型参数名描述
Tentity实体对象
WrapperupdateWrapper实体对象封装操作类 UpdateWrapper
CollectionentityList实体对象集合
intbatchSize插入批次数量

1.示例(saveOrUpdate)

// 假设有一个 User 实体对象,其中 id 是 TableId 注解的属性
User user = new User();
user.setId(1);
user.setName("John Doe");
user.setEmail("john.doe@example.com");
boolean result = userService.saveOrUpdate(user); // 调用 saveOrUpdate 方法
if (result) {
    System.out.println("User updated or saved successfully.");
} else {
    System.out.println("Failed to update or save user.");
}

生成的 SQL(假设 id 为 1 的记录已存在):

UPDATE user SET name = 'John Doe', email = 'john.doe@example.com' WHERE id = 1

生成的 SQL(假设 id 为 1 的记录不存在):

INSERT INTO user (id, name, email) VALUES (1, 'John Doe', 'john.doe@example.com')

2.示例(saveOrUpdateBatch)

// 假设有一组 User 实体对象,每个对象都有 id 属性
List<User> users = Arrays.asList(
    new User(1, "Alice", "alice@example.com"),
    new User(2, "Bob", "bob@example.com"),
    new User(3, "Charlie", "charlie@example.com")
);
// 使用默认批次大小进行批量修改插入
boolean result = userService.saveOrUpdateBatch(users); // 调用 saveOrUpdateBatch 方法,默认批次大小
if (result) {
    System.out.println("Users updated or saved successfully.");
} else {
    System.out.println("Failed to update or save users.");
}

生成的 SQL(假设 id 为 1 和 2 的记录已存在,id 为 3 的记录不存在):

UPDATE user SET name = 'Alice', email = 'alice@example.com' WHERE id = 1
UPDATE user SET name = 'Bob', email = 'bob@example.com' WHERE id = 2
INSERT INTO user (id, name, email) VALUES (3, 'Charlie', 'charlie@example.com')

3. 示例(saveOrUpdateBatch 指定批次大小)

// 假设有一组 User 实体对象
List<User> users = Arrays.asList(
    new User(4, "David", "david@example.com"),
    new User(5, "Eve", "eve@example.com"),
    new User(6, "Frank", "frank@example.com")
);
// 指定批次大小为 2进行批量修改插入
boolean result = userService.saveOrUpdateBatch(users, 2); // 调用 saveOrUpdateBatch 方法,指定批次大小
if (result) {
    System.out.println("Users updated or saved successfully.");
} else {
    System.out.println("Failed to update or save users.");
}

生成的 SQL(假设指定批次大小为 2):

-- 第一批次
UPDATE user SET name = 'David', email = 'david@example.com' WHERE id = 4
UPDATE user SET name = 'Eve', email = 'eve@example.com' WHERE id = 5

-- 第二批次
INSERT INTO user (id, name, email) VALUES (6, 'Frank', 'frank@example.com')

通过上述示例,我们可以看到 saveOrUpdate 系列方法是如何在 Service 层进行批量修改插入操作的,以及它们对应的 SQL 语句。这些方法提供了高效的数据操作方式,可以根据不同的条件进行更新或插入操作。

本质上就是先去根据主键id去查询数据是否存在,存在则根据id去更新,不存在就新增。

三、remove

// 根据 queryWrapper 设置的条件,删除记录
boolean remove(Wrapper<T> queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map<String, Object> columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);

功能描述: 通过指定条件删除符合条件的记录。
返回值: boolean,表示删除操作是否成功。
参数说明

类型参数名描述
WrapperqueryWrapper实体包装类 QueryWrapper
Serializableid主键 ID
Map<String, Object>columnMap表字段 map 对象
Collection<? extends Serializable>idList主键 ID 列表

1. 示例(remove)

// 假设有一个 QueryWrapper 对象,设置删除条件为 name = 'John Doe'
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "John Doe");
boolean result = userService.remove(queryWrapper); // 调用 remove 方法
if (result) {
    System.out.println("Record deleted successfully.");
} else {
    System.out.println("Failed to delete record.");
}

生成的 SQL:

DELETE FROM user WHERE name = 'John Doe'

2. 示例(removeById):

// 假设要删除 ID 为 1 的用户
boolean result = userService.removeById(1); // 调用 removeById 方法
if (result) {
    System.out.println("User deleted successfully.");
} else {
    System.out.println("Failed to delete user.");
}

生成的 SQL:

DELETE FROM user WHERE id = 1

3. 示例(removeByMap):

// 假设有一个 columnMap,设置删除条件为 age > 30
Map<String, Object> columnMap = new HashMap<>();
columnMap.put("age", 30);
boolean result = userService.removeByMap(columnMap); // 调用 removeByMap 方法
if (result) {
    System.out.println("Records deleted successfully.");
} else {
    System.out.println("Failed to delete records.");
}

生成的 SQL:

DELETE FROM user WHERE age > 30

4. 示例(removeByIds):

// 假设有一组 ID 列表,批量删除用户
List<Integer> ids = Arrays.asList(1, 2, 3);
boolean result = userService.removeByIds(ids); // 调用 removeByIds 方法
if (result) {
    System.out.println("Users deleted successfully.");
} else {
    System.out.println("Failed to delete users.");
}

生成的 SQL:

DELETE FROM user WHERE id IN (1, 2, 3)

通过上述示例,我们可以看到 remove 系列方法是如何在 Service 层进行删除操作的,以及它们对应的 SQL 语句。这些方法提供了灵活的数据操作方式,可以根据不同的条件进行删除操作。

四、update

// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper<T> whereWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);

功能描述: 通过指定条件更新符合条件的记录。
返回值: boolean,表示更新操作是否成功。
参数说明

类型参数名描述
WrapperupdateWrapper实体对象封装操作类 UpdateWrapper
Tentity实体对象
CollectionentityList实体对象集合
intbatchSize更新批次数量

1. 示例(update UpdateWrapper 形式):

// 假设有一个 UpdateWrapper 对象,设置更新条件为 name = 'John Doe',更新字段为 email
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name", "John Doe").set("email", "john.doe@newdomain.com");
boolean result = userService.update(updateWrapper); // 调用 update 方法
if (result) {
    System.out.println("Record updated successfully.");
} else {
    System.out.println("Failed to update record.");
}

生成的 SQL:

UPDATE user SET email = 'john.doe@newdomain.com' WHERE name = 'John Doe'

2. 示例(update WhereWrapper 形式):

// 假设有一个 User 实体对象,设置更新字段为 name,以及一个 whereWrapper 设置更新条件为 id = 1
User updateEntity = new User();
updateEntity.setName("Updated Name");
QueryWrapper<User> whereWrapper = new QueryWrapper<>();
whereWrapper.eq("id", 1);
boolean result = userService.update(updateEntity, whereWrapper); // 调用 update 方法
if (result) {
    System.out.println("Record updated successfully.");
} else {
    System.out.println("Failed to update record.");
}

生成的 SQL:

UPDATE user SET name = 'Updated Name' WHERE id = 1

整数类型如无特殊要求,可使用包装类

3. 示例(updateById):

// 假设有一个 User 实体对象,设置更新字段为 email,根据 ID 更新
User updateEntity = new User();
updateEntity.setId(1);
updateEntity.setEmail("updated.email@example.com");
boolean result = userService.updateById(updateEntity); // 调用 updateById 方法
if (result) {
    System.out.println("Record updated successfully.");
} else {
    System.out.println("Failed to update record.");
}

生成的 SQL:

UPDATE user SET email = 'updated.email@example.com' WHERE id = 1

4. 示例(updateBatchById):

// 假设有一组 User 实体对象,批量更新
List<User> users = Arrays.asList(
    new User(1, null, "new.email1@example.com"),
    new User(2, null, "new.email2@example.com")
);
boolean result = userService.updateBatchById(users); // 调用 updateBatchById 方法,默认批次大小
if (result) {
    System.out.println("Records updated successfully.");
} else {
    System.out.println("Failed to update records.");
}

生成的 SQL(假设默认批次大小为 2):

UPDATE user SET email = 'new.email1@example.com' WHERE id = 1
UPDATE user SET email = 'new.email2@example.com' WHERE id = 2

更新成功一条,即返回true

5. 示例(updateBatchById 指定批次大小):

// 假设有一组 User 实体对象,批量更新,并指定批次大小为 1
List<User> users = Arrays.asList(
    new User(1, null, "new.email1@example.com"),
    new User(2, null, "new.email2@example.com")
);
boolean result = userService.updateBatchById(users, 1); // 调用 updateBatchById 方法,指定批次大小
if (result) {
    System.out.println("Records updated successfully.");
} else {
    System.out.println("Failed to update records.");
}

生成的 SQL(假设指定批次大小为 1):

-- 第一批次
UPDATE user SET email = 'new.email1@example.com' WHERE id = 1
-- 第二批次
UPDATE user SET email = 'new.email2@example.com' WHERE id = 2

当值为null时不会更新该字段,可使用空字符串""代替

通过上述示例,我们可以看到 update 系列方法是如何在 Service 层进行更新操作的,以及它们对应的 SQL 语句。这些方法提供了灵活的数据操作方式,可以根据不同的条件进行更新操作。


总结

回到顶部

大家可以继承mybatis-plus提供的ServiceImpl<UserMapper, User>,它实现了IService,提供更多了方法。

官方给的用例太多了,一方面懒得复制想水一下,一方面又想把案例的每个用法带给兄弟们,好纠结啊!!!

虽然都是官方案例,但是还是建议大家跑一下,熟悉下API,查看API执行后打印的sql语句日志,代码写完之后多做测试,避免不必要的问题。

  • 43
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值