Ebean ORM框架介紹-1.增強註解

在瞭解Ebeam框架之前,一直都在使用JPA作爲Spring Boot的ORM框架。JPA用起來比較簡單的,對對象的增刪改操作,幾乎完全不需要接觸SQL語句,更適合領域驅動設計的建模方法。但對一些非業務操作的技術處理和查詢尤其是複雜查詢的支持較弱,這也是有人選擇Mybatis的重要原因。

Ebean ORM框架,可以說幾乎支持所有的JPA的功能同時也兼顧了Mybatis的靈活性,並且還有一些較實用的增加功能。本系列文章將一一介紹Ebean特有的較實用的功能。今天介紹Ebean的增強註解功能。

ebean文檔 https://ebean.io/docs/

一、數據庫支持

Ebean和JPA類似可支持多種數據庫

Summary

Platform Identity DbArray DbJson UUID History
H2 *Identity & Sequence Partial Simulated Native Triggers
Postgres *Identity & Sequence Full Full Native Triggers
MySql Identity Simulated Full Triggers
SQL Server 17 *Sequence & Identity Simulated Full Native Native
SQL Server 16 *Identity Simulated Full Native
Oracle *Sequence & Identity Simulated Full Native
DB2 *Identity & Sequence None
SAP Hana - -
SQLite *Identity Partial Simulated None
ClickHouse - -
Cockroach - -
NuoDB - -

引用至:https://ebean.io/docs/database/

二、安裝ebean插件

想要在idea使用調試代碼必須要安裝Ebean enhancer插件

  1. 打開idea, File > Settings > Plugins > Ebean enhancer 來安裝插件,如圖所示:

  1. 啓用ebean增加工具,確保build下的 "Ebean enhancer"前面有一個勾

如果不勾運行的時候就可能報錯

三、註解介紹

public abstract class BaseModel extends Model {

  @Id
  long id;

  @Version
  Long version;

  @WhenCreated
  Instant whenCreated;

  @WhenModified
  Instant whenModified;
}


public class Customer extends BaseModel {

  public enum Status {
    @EnumValue("N")
    NEW,
    @EnumValue("A")
    APPROVED,
    @EnumValue("S")
    SHIPPED,
    @EnumValue("C")
    COMPLETE,
    @EnumValue("F")
    FOO

  }

  @DbComment("the name")
  private String name;

  @DbArray
  @DbComment("the array")
  private List<UUID> uids = new ArrayList<>();

  @DbJson
  private SomeEmbedd some;

  @SoftDelete
  private boolean deleted;

  Status status;

  @DbMap(length = 800)
  Map<String, SomeEmbedd> map;
}

數據庫格式:

1. @WhenCreated、@WhenModified

記錄的創建時間和最後修改時間

jpa:

@PrePersist
public void preCreate() {
  createTime = new Date();
  updateTime = createTime;
}

@PreUpdate
public void preUpdate() {
	updateTime = new Date();
}

2. @DbComment("the name")

數據庫字段註釋

jpa :

 @Column(columnDefinition = "int(11) DEFAULT NULL COMMENT '類型'")

3. @DbArray

以數組形成存儲數據,數據庫字段爲字符串,相當於架構自行做了格式轉換。在數據量不太大的場景可以使用這種方式。

4. @DbJson

和@DbArray類似,以json類型存儲,架構做格式轉換

@Embeddable
public class SomeEmbedd {

  String one;
  String two;
  String three;
}

@Embeddable配合使用可將對象轉爲JSON類型保存在數據庫中

5. @DbMap

和@DbArray類似,以map轉爲字符串存儲,架構做格式轉換

6. @SoftDelete

軟刪除,對架構實現此功能,並對架構提供的查詢語法有效,這個功能還是挺實用的。

7. @EnumValue

枚舉值映射

  public enum Status {
    @EnumValue("N")
    NEW,
    @EnumValue("A")
    APPROVED,
    @EnumValue("S")
    SHIPPED,
    @EnumValue("C")
    COMPLETE,
    @EnumValue("F")
    FOO
  }

Jpa:

@Enumerated(EnumType.STRING)
private Status customerStatus

jpa使用 @Enumerated 註解可映射枚舉值字符串或枚舉索引值到數據庫,如果想自定義需要寫一定的代碼,而 @EnumValue配置起來較靈活

四、配置

1. maven配置

<!-- Query bean support -->
<dependency>
    <groupId>io.ebean</groupId>
    <artifactId>ebean-querybean</artifactId>
    <version>${ebean.version}</version>
</dependency>

<!-- APT Query bean generation for Java -->
<dependency>
    <groupId>io.ebean</groupId>
    <artifactId>querybean-generator</artifactId>
    <version>${ebean.version}</version>
    <scope>provided</scope>
</dependency>


<!-- Test dependencies -->
<!-- includes docker test database container support  -->
<dependency>
    <groupId>io.ebean</groupId>
    <artifactId>ebean-test</artifactId>
    <version>${ebean.version}</version>
    <scope>test</scope>
</dependency>

...

<plugin>
  <groupId>io.repaint.maven</groupId>
  <artifactId>tiles-maven-plugin</artifactId>
  <version>2.18</version>
  <extensions>true</extensions>
  <configuration>
    <tiles>
      <!-- other tiles ... -->
      <tile>io.ebean.tile:enhancement:12.6.2</tile>
    </tiles>
  </configuration>
</plugin>

2. YAML配置

正式application.yaml 此處必須是YAML

datasource:
  db:
    username: root
    password: 123456
    url: jdbc:mysql://./db_customer

單元測試application.yaml

ebean:
  migration:
    run: run

  test:
    platform: mysql # h2, postgres, mysql, oracle, sqlserver, sqlite
    ddlMode: none # none | dropCreate | create | migration | createOnly | migrationDropCreate
    dbName: my_app
    mysql:
      version: 5.7
      containerName: ms55
      collation: utf8mb4_unicode_ci
      characterSet: utf8mb4

這個是個docker的數據庫測試環境,只要本機有安裝好docker,進行單元測試時可自動創建image並運行。

並可以通過工具連接:

username: {databaseName}
password: test
port: 4306
url: jdbc:mysql://localhost:{port}/{databaseName}
driver: com.mysql.jdbc.Driver
image: mysql:{version}

五、模型操作

1. 使用Model內聯操作

使用JPA時,模型的增刪改需要引入Repository來操作,Ebean的模型直接承繼系統的Model類,可實現內聯操作

public class Customer extends Model {
	...
}

@Test
public void create() {

  Customer customer = Customer.builder()
    .name("hy")
    .phone("13812345678")
    .build();
  customer.save();
}

@Test
public void update() {
  Customer customer = Customer.find.byId(1L);
  Optional.ofNullable(customer).ifPresent(o -> {
    o.setName(UUID.randomUUID().toString());
    o.save();
  });
}

@Test
public void delete() {
  Customer customer = Customer.find.byId(1L);
  System.err.println(customer);
  Optional.ofNullable(customer).ifPresent(o -> {
    o.delete();
  });
}

查詢操作:

public class CustomerFinder extends Finder<Long, Customer> {
  public CustomerFinder() {
    super(Customer.class);
  }
}

public class Customer extends Model {
	public static final CustomerFinder find = new CustomerFinder();
  ...
}

@Test
public void find() {
  Customer customer = Customer.find.byId(1L);
}

內聯操作從代碼上看起來優雅了很多,也簡化了代碼。但在某種層面上也增加了入侵性,沒有面向接口倉庫實現方式解耦,當然你也可以選擇使用Repository方式

六、綜述

Ebean還有很多JPA沒有的高級功能,如歷史記錄、草稿、加密、複合查詢、多數據支持、多租戶等等功能,後續期待更新。

文中代碼由於篇幅原因有一定省略並不是完整邏輯,如有興趣請Fork源代碼 https://gitee.com/hypier/barry-ebean

七、請關注我的公衆號

請關注我的公衆號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章