mapper层 @Repository public interface UserMapper extends BaseMapper<User>
BaseMapper中封装好了增删改查的方法
后面直接调用就好了
测试类
@SpringBootTest public class CrudTest {@Autowiredprivate UserMapper userMapper;//新增@Testpublic 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删除@Testpublic void deleteById(){userMapper.deleteById("1687729477728641025");}//根据Map类型删除@Testpublic void deleteByMap(){Map<String,Object> map = new HashMap<>();map.put("name","Billie");//设置根据哪些值删除map.put("age",24);userMapper.deleteByMap(map);//需要map作为参数}//批量删除@Testpublic 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修改@Testpublic void UpdateById(){User user = new User();user.setId(3L);//需要设置iduser.setAge(30);int result = userMapper.updateById(user);System.out.println(result);}//通过对id进行查询@Testpublic void testSelectById(){User user = userMapper.selectById(3L);System.out.println(user);}//批量查询,注意Arrays.asList(3L, 4L),这个是把要查询的id放到数组里@Testpublic void testSelectByBatchIds(){List<Long> list = Arrays.asList(3L, 4L);List<User> users = userMapper.selectBatchIds(list);System.out.println(users);}//通过map进行查询@Testpublic void testSelectBymaps(){Map<String,Object> map = new HashMap<>();map.put("name","Sandy");map.put("age",21);List<User> users = userMapper.selectByMap(map);//需要创建map对象}//查询全部,有条件构造器,查询全部可以用null@Testpublic void testSelectByAll(){List<User> users = userMapper.selectList(null);//条件构造器,没有条件的时候可以使用nullusers.forEach(System.out::println);} }
-----------------------------------------------------------------
public interface UserService extends IService<User> { }
@Service//标识为一个组件 public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{ }
ServiceImpl中封装了方法(特别注意批量添加只有serviceImpl中有)
测试类
@SpringBootTest public class MybatisPlusServiceTest {@Autowiredprivate UserService userService;@Testpublic void testCount(){long count = userService.count();System.out.println("总记录数为:"+count);}//测试批量添加,只有service层中有批量添加//userService.saveOrUpdate();有id修改,无id添加@Testpublic 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);} }