跳到主要内容

Service CRUD 接口(不推荐)

准备以下接口和实现类

UserService接口

public interface UserService extends IService<User> {
}

UserServiceImpl实现类

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
}

1698757206485

提示

个人不推荐使用的原因,实现IService接口后,会变得很重,Service有的方法,Mapper也够用,以下是个人认为比较好用的两个方法

Save方法

// 插入(批量)
boolean saveBatch(Collection<T> entityList);

SaveOrUpdate方法

//存在更新记录,否则插入一条记录
boolean saveOrUpdate(T entity);

方法测试

boolean saveBatch(Collection<T> entityList);

@Autowired
private UserService userService;

@Test
void test() {
List<User> userList = List.of(
new User(null, "a", 18, "a@163.com"),
new User(null, "b", 19, "b@163.com"),
new User(null, "c", 20, "c@163.com"),
new User(null, "d", 21, "d@163.com"),
new User(null, "e", 22, "e@163.com")
);
boolean b = userService.saveBatch(userList);
System.out.println("b = " + b);
}

返回值为布尔值

image-20231031210621097

boolean saveOrUpdate(T entity);

@Autowired
private UserService userService;

@Test
void test() {
User user = new User(123L, "老王", 22, "123@163.com");
boolean b = userService.saveOrUpdate(user);
System.out.println("b = " + b);
}

第一次执行为新增

image-20231031211308071

再次执行为修改数据

@Autowired
private UserService userService;

@Test
void test() {
User user = new User(123L, "老王2", 23, "123@163.com");
boolean b = userService.saveOrUpdate(user);
System.out.println("b = " + b);
}

image-20231031211429341