活动记录和正常的CRUD效果是一样的,此处只当一个拓展,了解即可
pom.xml
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/p6spy/p6spy --> <dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>3.8.0</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.49</version> <scope>test</scope> </dependency> <!-- for testing --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
配置类
@Configuration @MapperScan("com.mp.record.mapper") public class MybatisPlusConfig { }
实体类
@EqualsAndHashCode(callSuper = true) @Data @Accessors(chain = true) public class User extends Model<User> { private Long id; private String name; private Integer age; private String email; @Override protected Serializable pkVal() { /** * AR 模式这个必须有,否则 xxById 的方法都将失效! * 另外 UserMapper 也必须 AR 依赖该层注入,有可无 XML */ return id; } }
Mapper层
/** * <p> * 这个得有,就算不去用它否则默认不注入 * </p> * <p> * MP 支持不需要 UserMapper.xml 这个模块演示内置 CRUD 咱们就不要 XML 部分了 * </p> * */ public interface UserMapper extends BaseMapper<User> { }
application.yml
spring: datasource: driver-class-name: com.p6spy.engine.spy.P6SpyDriver url: jdbc:p6spy:h2:tcp://192.168.180.115:19200/~/mem/test username: root password: test
测试类
@SpringBootTest class RecordApplicationTests { @Test public void aInsert() { User user = new User(); user.setName("咩咩"); user.setAge(5); user.setEmail("[email protected]"); //INSERT INTO user ( id, name, email, age ) VALUES ( 1190527412941651970, '咩咩', '[email protected]', 5 ) Assert.assertTrue(user.insert()); // 成功直接拿会写的 ID System.err.println("\n插入成功 ID 为:" + user.getId()); } @Test public void bDelete() { Assert.assertTrue(new User().setId(3L).deleteById()); Assert.assertTrue(new User().delete(new QueryWrapper<User>() .lambda().eq(User::getName, "Sandy"))); } @Test public void cUpdate() { Assert.assertTrue(new User().setId(1L).setEmail("[email protected]").updateById()); Assert.assertTrue(new User().update(new UpdateWrapper<User>().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<User>().lambda().eq(User::getId, 2)); Assert.assertEquals("Jack", user.getName()); Assert.assertTrue(3 == user.getAge()); } }