展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

ActiveRecord

  • pom.xml
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
  • 配置类
@Configuration
@MapperScan("com.baomidou.mybatisplus.samples.ar.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
    public Serializable pkVal() {
        /**
         * AR 模式这个必须有,否则 xxById 的方法都将失效!
         * 另外 UserMapper 也必须 AR 依赖该层注入,有可无 XML
         */
        return id;
    }
}
  • 测试
@SpringBootTest
public class ActiveRecordTest {

    /**
     * INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
     * 1549932146396479489(Long), 咩咩(String), 5(Integer), miemie@mp.com(String)
     *
     * 插入成功 ID 为:1549932146396479489
     */
    @Test
    public void aInsert() {
        User user = new User();
        user.setName("咩咩");
        user.setAge(5);
        user.setEmail("miemie@mp.com");
        Assertions.assertTrue(user.insert());
        // 成功可以直接获取 ID
        System.err.println("\n插入成功 ID 为:" + user.getId());
    }

    /**
     * DELETE FROM user WHERE id=?
     * 3(Long)
     *
     * DELETE FROM user WHERE (name = ?)
     * Sandy(String)
     */
    @Test
    public void bDelete() {
        Assertions.assertTrue(new User().setId(3L).deleteById());
        Assertions.assertTrue(new User().delete(new QueryWrapper<User>()
                .lambda().eq(User::getName, "Sandy")));
    }

    /**
     * UPDATE user SET email=? WHERE id=?
     * ab@c.c(String), 1(Long)
     *
     * UPDATE user SET age=? WHERE (id = ?)
     * 3(Integer), 2(Integer)
     */
    @Test
    public void cUpdate() {
        Assertions.assertTrue(new User().setId(1L).setEmail("ab@c.c").updateById());
        Assertions.assertTrue(new User().update(new UpdateWrapper<User>().lambda()
                        .set(User::getAge, 3).eq(User::getId, 2)));
    }

    /**
     * SELECT id,name,age,email FROM user WHERE id=?
     * 1(Long)
     *
     * SELECT id,name,age,email FROM user WHERE (id = ?)
     * 2(Integer)
     */
    @Test
    public void dSelect() {
        //Assertions.assertEquals("ab@c.c", new User().setId(1L).selectById().getEmail());
        System.out.println(new User().setId(1L).selectById().getEmail());
        User user = new User().selectOne(new QueryWrapper<User>().lambda().eq(User::getId, 2));
        System.out.println(user.getName());
        System.out.println(user.getAge());
//        Assertions.assertEquals("Jack", user.getName());
//        Assertions.assertTrue(3 == user.getAge());
    }

}
posted @ 2022-07-21 09:46  DogLeftover  阅读(66)  评论(0编辑  收藏  举报