Active Record(活动记录),是一种领域模型模式,特点是一个模型类对应关系型数据库中的一个表,而模型类的一个实例对应表中的一行记录。
ActiveRecord 一直广受动态语言( PHP 、 Ruby 等)的喜爱,而 Java 作为准静态语言, 对于 ActiveRecord 往往只能感叹其优雅,所以 MP 也在 AR 道路上进行了一定的探索
支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
一.AR模式和MP的Mapper模式的比较
1.原有MP的Mapper模式
①创建项目完成Spring和MP的集成
②创建数据库表对应的实体类
③创建mapper接口并继承BaseMapper接口
④从Spring容器中获取Mapper接口的实例化对象完成数据库操作
描述:
通过以上流程,MP的操作模式较于原有Mybatis的数据库操作流程
没有任何变化,只是我们在编写代码的时候不用在mapper层声明
Sql语句或者XML文件了,提升开发效率。
2.MP的AR模式
①创建项目完成Spring和MP的集成
②创建数据库表对应的实体类,继承Model类
③在实体类中覆写pkVal方法.
④创建Mapper接口并继承BaseMapper接口
⑤创建Spring对象,让Spring容器完成对Mapper层的实例化扫描
⑥创建实体类对象,直接调用实体类从Model中继承的数据库方法完成
数据库操作。
3.流程比较分析
MP的AR模式其实底层仍然使用的是Mapper层在完成数据库操作。
只不过由我们自己调用Mappe对象操作数 据库,变成了通过
实体类对象来调用Mapper完成数据库操作。从代码的物理视图上
我们是看不到实体类调用Mapper的过程的。也就说,本质上仍然
是Mapper层在操作数据库
实体类型操作数据掩盖了地产的mapper的方法的调用
二.AR模式的使用代码示例
1.创建一个集成了MP的SSM项目
2.在pojo层创建实体类,并继承Model类,覆写pkVal的方法
public class User extends Model<User> {
@TableId(type = IdType.AUTO)
private Integer id;
private String name;
private String password;
private Integer age;
@Override
protected Serializable pkVal() {
return this.id;
}
3.不要忘了写Mapper
public interface StudentMapper extends BaseMapper {
}
4.测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.xml")
public class Test02 {
@Autowired
private UserMapper userMapper;
/**
* 增加
*/
@Test
public void insert() {
User user = new User("拾亿", "123", 12);
boolean insert = user.insert();
}
/**
* 增加或者更新
*/
@Test
public void insertOrUpdate() {
User user = new User(11, "拾亿", "123", 12);
boolean insert = user.insertOrUpdate();
}
/**
* 查询
*/
@Test
public void select() {
User user = new User();
user.setId(10);
User user1 = user.selectById();
System.out.println(user1);
}
/**
* 更新
*/
@Test
public void update() {
User user = new User();
user.setId(10);
user.setName("牛肉干");
user.setAge(13);
boolean b = user.updateById();
}
/**
* 删除
*/
@Test
public void delete() {
User user = new User();
user.setId(10);
boolean b = user.deleteById();
}
}