MybatisPlus使用Model实现CRUD

Model是mybatisPlus自带的实体父类。

import com.baomidou.mybatisplus.extension.activerecord.Model;

直接定义Bean的时候实现Model类,该类的作用是能通过实体直接进行crud操作,而不需要进行调用dao,前提是“必须存在对应的原始mapper并继承baseMapper并且可以使用的前提下”。也就是说实际上行还是调用的dao的方法。

@EqualsAndHashCode(callSuper = true)
@Data
@Accessors(chain = true)
public class User extends Model {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
必须写入mapper
public interface UserMapper extends BaseMapper {

}

Model类 自身实现了 insert() ,insertOrUpdate(),deleteById(Serializable id),deleteById() ,delete(Wrapper queryWrapper),updateById(),update(Wrapper updateWrapper),selectAll(),selectList(Wrapper queryWrapper),selectOne(Wrapper queryWrapper),selectPage(E page, Wrapper queryWrapper),selectCount(Wrapper queryWrapper)

@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest {

    @Test
    public void aInsert() {
        User user = new User();
        user.setName("咩咩");
        user.setAge(5);
        user.setEmail("[email protected]");
        Assert.assertTrue(user.insert());
        // 成功可以直接获取 ID
        System.err.println("\n插入成功 ID 为:" + user.toString());
    }


    @Test
    public void bDelete() {
        Assert.assertTrue(new User().setId(3L).deleteById());
        Assert.assertTrue(new User().delete(new QueryWrapper()
                .lambda().eq(User::getName, "Sandy")));
        List userList=new User().selectAll();
        userList.forEach(u->System.out.print(u));
    }


    @Test
    public void cUpdate() {
        Assert.assertTrue(new User().setId(1L).setEmail("[email protected]").updateById());
        Assert.assertTrue(new User().update(new UpdateWrapper().lambda()
                        .set(User::getAge, 3).eq(User::getId, 2)));
    }


    @Test
    public void dSelect() {
        Assert.assertEquals("[email protected]", new User().setId(1L).selectById().getEmail());
        User user = new User().selectOne(new QueryWrapper().lambda().eq(User::getId, 2));
        Assert.assertEquals("Jack", user.getName());
        Assert.assertTrue(3 == user.getAge());
    }

    @Test
    public void dSelectPage() {
        IPage userIPage=new Page<>(1,10);
        LambdaQueryWrapper queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAge,20);
        userIPage = new User().selectPage(userIPage,queryWrapper);
        userIPage.getRecords().forEach(i -> System.out.println(i));
    }
}

你可能感兴趣的:(spring-boot)