Service
1、通用Service接口
可以看官网的CRUD接口
https://baomidou.com/pages/49cc81/
在example包下创建接口service.UserService
package com.example.service.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.pojo.User;
public interface UserService extends IService<User> {
}
在service包下创建文件impl.UserServiceImpl
@Service
package com.example.service.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.UserMapper;
import com.example.pojo.User;
import com.example.service.service.UserService;
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
ServiceImpl<UserMapper, User>
UserMapper:自己创建的接口类
User:自己创建的实体类
2、测试通用Service之查询总记录数
创建测试文件
package com.example.mybatisplus;
import com.example.service.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class MybatisPlusServiceTest {
@Autowired
private UserService userService;
@Test
public void test1(){
long count = userService.count();
System.out.println("总结记录数:"+count);
}
}
3、测试通用Service之批量添加功能
如果用BaseMapper的基本insert添加数据,如果以后有几千行甚至几万行数据需要添加,需要多少代码?这时候需要这个通用接口来实现
public void testInsertMore(){
List<User> list=new ArrayList<>();
for (int i = 0; i <=10; i++) {
User user=new User();
user.setName("lisi"+i);
user.setAge(20+i);
list.add(user);
}
boolean b = userService.saveBatch(list);
System.out.println(b);
}
|