mapper层 @Repository public interface UserMapper extends BaseMapper<User>
BaseMapper中封装好了增删改查的方法
后面直接调用就好了
测试类文章来源地址https://www.toymoban.com/news/detail-627289.html
@SpringBootTest public class CrudTest { @Autowired private UserMapper userMapper; //新增 @Test public void insert(){//没有返回值,不需要调用 User user =new User(); user.setAge(23); user.setName("llx"); user.setEmail("lao123@123.com"); int result = userMapper.insert(user);//新增一条数据,需要创建对象,赋值 System.out.println(result); } //根据id删除 @Test public void deleteById(){ userMapper.deleteById("1687729477728641025"); } //根据Map类型删除 @Test public void deleteByMap(){ Map<String,Object> map = new HashMap<>(); map.put("name","Billie");//设置根据哪些值删除 map.put("age",24); userMapper.deleteByMap(map);//需要map作为参数 } //批量删除 @Test public void deletByCatchId(){ List<Long> list = Arrays.asList(1L, 2L);//数据库是long类型的 //Arrays.asList(1L, 2L)将数据转换为List集合 int result = userMapper.deleteBatchIds(list); System.out.println(result); } //通过id修改 @Test public void UpdateById(){ User user = new User(); user.setId(3L);//需要设置id user.setAge(30); int result = userMapper.updateById(user); System.out.println(result); } //通过对id进行查询 @Test public void testSelectById(){ User user = userMapper.selectById(3L); System.out.println(user); } //批量查询,注意Arrays.asList(3L, 4L),这个是把要查询的id放到数组里 @Test public void testSelectByBatchIds(){ List<Long> list = Arrays.asList(3L, 4L); List<User> users = userMapper.selectBatchIds(list); System.out.println(users); } //通过map进行查询 @Test public void testSelectBymaps(){ Map<String,Object> map = new HashMap<>(); map.put("name","Sandy"); map.put("age",21); List<User> users = userMapper.selectByMap(map);//需要创建map对象 } //查询全部,有条件构造器,查询全部可以用null @Test public void testSelectByAll(){ List<User> users = userMapper.selectList(null);//条件构造器,没有条件的时候可以使用null users.forEach(System.out::println); } }
-----------------------------------------------------------------
public interface UserService extends IService<User> { }
@Service//标识为一个组件 public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{ }
ServiceImpl中封装了方法(特别注意批量添加只有serviceImpl中有)文章来源:https://www.toymoban.com/news/detail-627289.html
测试类
@SpringBootTest public class MybatisPlusServiceTest { @Autowired private UserService userService; @Test public void testCount(){ long count = userService.count(); System.out.println("总记录数为:"+count); } //测试批量添加,只有service层中有批量添加 //userService.saveOrUpdate();有id修改,无id添加 @Test public void testInsertMore(){ List<User> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { User user = new User(); user.setName("abc"+i); user.setAge(20+i); list.add(user); } boolean b = userService.saveBatch(list); System.out.println(b); } }
到了这里,关于MybatisPlus-CRUD,不带条件构造器的常用方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!