Prior to learning about the Ebeam framework, I had been using JPA as the ORM framework for Spring Boot. JPA is more suitable for domain-driven design modeling because it is relatively simple to add, delete and modify objects without touching SQL statements at all. However, the technical processing and query support for some non-business operations, especially complex query, is weak, which is also an important reason why some people choose Mybatis.

Ebean ORM framework, can be said to support almost all the functions of JPA while also taking into account the flexibility of Mybatis, and there are some more practical added functions. This series of articles introduces the more useful features that are unique to eBeans. Today we introduce the enhanced annotation capabilities of eBeans.

Ebean document ebean. IO/docs /

First, database support

Ebeans, like JPA, support multiple databases

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

Refer to:Ebean. IO/docs/databa…

Install the eBean plug-in

To use debug code in IDEA, you must install the Ebean enhancer plug-in

  1. Open idea, File > Settings > Plugins > Ebean enhancer to install the plugin, as shown in the figure below:

  1. Enable the eBean enhancer tool and make sure “ebean enhancer” is preceded by a check box under build

An error may occur if the check box is not checked

Three, notes and introduction

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;
}

Copy the code

Database format:

1. @ WhenCreated, @ WhenModified

Record the creation time and last modification time

Jpa:

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

@PreUpdate
public void preUpdate(a) {
	updateTime = new Date();
}
Copy the code

2. @DbComment(“the name”)

Database field annotation

Jpa:

 @column (columnDefinition = "int(11) DEFAULT NULL COMMENT 'type '")
Copy the code

3. @DbArray

The data is stored in arrays and the database fields are strings, which is equivalent to the schema format conversion itself. This method can be used in scenarios with a small amount of data.

4. @DbJson

Similar to @dbarray, it is stored in JSON format

@Embeddable
public class SomeEmbedd {

  String one;
  String two;
  String three;
}
Copy the code

Used in conjunction with @embeddable to convert objects to JSON type and store them in a database

5. @DbMap

Similar to @dbarray, map to string storage, schema for format conversion

6. @SoftDelete

Soft delete, for the schema to implement this function, and the query syntax provided by the schema, this function is quite practical.

7. @EnumValue

Enumerated value mapping

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

Jpa:

@Enumerated(EnumType.STRING)
private Status customerStatus
Copy the code

Jpa uses the @Enumerated annotation to map enumeration strings or enumeration index values to the database, which requires some code to customize, whereas @EnumValue is more flexible to configure

Four, configuration,

1. The maven configurations

<! -- 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>
Copy the code

2. The YAML configuration

Formal application.yaml here must be YAMl

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

Unit test 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
Copy the code

This is a docker database test environment, as long as the machine has docker installed, the unit test can automatically create image and run.

And can be connected through tools:

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

5. Model operation

1. Use Model inline operations

With JPA, the addition, deletion and modification of models need to be implemented by importing Repository, and the Model of Ebean directly inherits the Model class of the system to achieve inline operations

public class Customer extends Model {... }@Test
public void create(a) {

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

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

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

Query operation:

public class CustomerFinder extends Finder<Long.Customer> {
  public CustomerFinder(a) {
    super(Customer.class); }}public class Customer extends Model {
	public static final CustomerFinder find = newCustomerFinder(); . }@Test
public void find(a) {
  Customer customer = Customer.find.byId(1L);
}
Copy the code

Inline operations look much more elegant from the code and simplify the code. But it is also intrusive in a way that is not decoupled from the interface oriented Repository implementation. Of course, you can also choose to use Repository

Six, review

Ebean also has many advanced features that JPA does not have, such as history, drafts, encryption, composite queries, multi-data support, multi-tenancy, etc. Expect updates.

The code in this article due to the length of reasons have some omission is not complete logic, if interested please Fork source code gitee.com/hypier/barr…