最近一直在用 Spring Boot 开发,项目中用到的 ORM 框架有:Spring Data JPA,Spring Data MongoDB,Mybatis,MyBatis Plus。
对照 Martin Fowler 的 Catalog of Patterns of Enterprise Application Architecture,我们分别列出 Spring Data,Mybatis,Mybatis Plus 使用的设计模式。
ORM Framework | Design Pattern |
Spring Data | Repository |
Mybatis | Data Mapper |
Mybatis Plus | Data Mapper & Active Record |
作为对比,我们看一下常用的 PHP ORM 框架使用的设计模式。
ORM Framework | Design Pattern |
Yii Active Record | Active Record |
Laravel Eloquent | Active Record |
Symfony Doctrine | Data Mapper |
可以看出 Java ORM 框架更喜欢 Data Mapper 设计模式,而 PHP ORM 框架更喜欢 Active Record 模式。
再看一下其他语言的 ORM 框架:
ORM Framework | Design Pattern |
Ruby on Rails | Active Record |
Django | Active Record |
Mongoose | Active Record |
不管是 Ruby on Rails(Ruby), 还是 Django(Python),或者 Mongoose(Node.js),都偏爱 Active Record 模式。
Active Record vs Data Mapper
作为两种非常常见的设计模式,让我们稍微花点时间了解一下 Active Record 和 Data Mapper 的区别。
首先我们还是参考 Martin Fowler 的 Catalog of Patterns of Enterprise Application Architecture 对比一下两种设计模式。
Active Record

Data Mapper

从图上可以看出来,两种设计模式最直观的区别是:Active Record 模式只定义了一个 Person 类,Data Mapper 模式需要定义 Person 类和 PersonMapper 类。
然后我们来对比一下两种模式代码上的区别:
Active Record
Person person = new Person();
person.firstName = "firstName";
person.lastName = "lastName";
person.insert();
Data Mapper
Person person = new Person();
person.firstName = "firstName";
person.lastName = "lastName";
personMapper.insert(person);
我个人更喜欢 Active Record 模式,不知道你们喜欢那种设计模式呢?
参考:
https://www.martinfowler.com/eaaCatalog/index.html
https://www.martinfowler.com/eaaCatalog/dataMapper.html
https://www.martinfowler.com/eaaCatalog/activeRecord.html
https://spring.io/projects/spring-data-jpa
http://www.mybatis.org/mybatis-3/
https://www.yiiframework.com/doc/guide/2.0/en/db-active-record
https://laravel.com/docs/5.8/eloquent
https://symfony.com/doc/current/doctrine.html
https://guides.rubyonrails.org/active_record_basics.html
https://docs.djangoproject.com/en/2.2/topics/db/models/
1,198 total views, 1 views today