ActiveRecord
本文与官网大多数一致,只是在示例中加入了一些实际验证的代码,日志可能和与官网略有出入(预估是因为版本原因)
本文测试代码中mybatis-plus依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.7</version>
</dependency>
ActiveRecord 模式是一种设计模式,它允许实体类直接与数据库进行交互,实体类既是领域模型又是数据访问对象。在 Mybatis-Plus 中,实体类只需继承 Model 类即可获得强大的 CRUD 操作能力。
注:在这个实体类使用ActiveRecord时必须保证这个实体类有对应的BaseMapper,否则会抛出异常
使用示例
// sql
// create table purchase_order
// (
// id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
// username CHAR(10) UNIQUE NOT NULL,
// state INT,
// create_time TIME,
// update_time TIME
// );
/*************************************************************************/
@Data
@TableName("purchase_order")
public class PurchaseOrderPo extends Model<PurchaseOrderPo> {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String username;
private int state;
private Date createTime;
private Date updateTime;
}
/*************************************************************************/
public interface PurchaseOrderMapper extends BaseMapper<PurchaseOrderPo> {
}
/*************************************************************************/
@Test
public void testInsert() {
PurchaseOrderPo purchaseOrderPo = new PurchaseOrderPo();
purchaseOrderPo.setUsername("李一二");
purchaseOrderPo.setState(1);
purchaseOrderPo.setCreateTime(new Date());
purchaseOrderPo.setUpdateTime(new Date());
purchaseOrderPo.insert();
}
// ==> Preparing: INSERT INTO purchase_order ( username, state, create_time, update_time ) VALUES ( ?, ?, ?, ? )
// ==> Parameters: 李一二(String), 1(Integer), 2024-08-19 11:12:10.193(Timestamp), 2024-08-19 11:12:10.193(Timestamp)
// <== Updates: 1
/*************************************************************************/
@Test
public void testDelete() {
PurchaseOrderPo purchaseOrderPo = new PurchaseOrderPo();
QueryWrapper<PurchaseOrderPo> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("username","李一二");
purchaseOrderPo.delete(queryWrapper);
}
// ==> Preparing: DELETE FROM purchase_order WHERE (username = ?)
// ==> Parameters: 李一二(String)
// <== Updates: 0
/*************************************************************************/
@Test
public void testDelete2() {
PurchaseOrderPo purchaseOrderPo = new PurchaseOrderPo();
purchaseOrderPo.setId(1);
purchaseOrderPo.deleteById();
}
// ==> Preparing: DELETE FROM purchase_order WHERE id=?
// ==> Parameters: 1(Integer)
// <== Updates: 1
/*************************************************************************/
@Test
public void testUpdate() {
PurchaseOrderPo purchaseOrderPo = new PurchaseOrderPo();
purchaseOrderPo.setId(3);
purchaseOrderPo.setUpdateTime(new Date());
purchaseOrderPo.updateById();
}
// ==> Preparing: UPDATE purchase_order SET state=?, update_time=? WHERE id=?
// ==> Parameters: 0(Integer), 2024-08-19 11:21:35.807(Timestamp), 3(Integer)
// <== Updates: 1
通过使用 ActiveRecord 模式,开发者可以更加简洁地编写数据库操作代码,同时保持代码的清晰和可维护性。这种模式尤其适合于简单的 CRUD 操作,可以大大减少重复代码的编写。
评论区