[JAVA] Getting Started with Doma-Introduction to the Criteria API

Introduction

Doma is a database access framework that runs on Java 8 and above. You can access databases for which JDBC drivers are provided, such as MySQL, PosgreSQL, Microsoft SQL Sever, and H2 Database.

Recent versions of Doma have added a new API for type-safe SQL construction, the Criteira API (https://doma.readthedocs.io/en/2.43.0/criteria-api/). This article introduces the Criteria API based on the latest version 2.43.0 at the time of writing.

Definition of entity class

Suppose you have a database schema that looks like this:

create table employee (
    id integer not null primary key,
    name varchar(255) not null,
    age integer not null, 
    version integer not null);

The entity class corresponding to the above table can be defined as follows:

@Entity(metamodel = @Metamodel)
public class Employee {
  @Id
  public Integer id;
  public String name;
  public Integer age;
  @Version public Integer version;
}

At first glance, it's a normal entity class definition, but notice that the @ Entity declaration says metamodel = @Metamodel. This description is very important, and compiling with the proper settings will generate a metamodel class called `ʻEmployee_`` in the same package as the Employee class.

Contents of the memo model class

For the sake of clarity, I'll omit it a bit, but the metamodel class ʻEmployee_` looks like this:

public final class Employee_ implements EntityMetamodel<Employee> {
  public final PropertyMetamodel<java.lang.Integer> id = ...;
  public final PropertyMetamodel<java.lang.String> name = ...;
  public final PropertyMetamodel<java.lang.Integer> age = ...;
  public final PropertyMetamodel<java.lang.Integer> version = ...;
}

The point of this metamodel class is that it has properties with the same names as the properties of the entity class, such as ʻid, name, ʻage, version. It also has property type information in the entity class.

The following is an example of actually constructing SQL using this metamodel class and the Criteria API.

Using the Criteria API

The Criteria API can be used anywhere, but it will be easier to understand if you create a class named xxxRepository and use it in it, for example:

public class EmployeeRepository {

  private final Entityql entityql;

  public EmployeeRepository(Config config) {
    this.entityql = new Entityql(config);
  }

  public Employee selectById(Integer id) {
    //Metamodel generation
    Employee_ e = new Employee_();
    //Assemble SQL using metamodel and get result
    return entityql.from(e).where(c -> c.eq(e.id, id)).fetchOne();
  }
}

The content of the selectById method of the above class is an example of using the Criteria API. This method uses the metamodel class and the ʻEntityql` class, which is the entry point of the Criteria API, to assemble SQL and get the execution result as one entity.

The SQL that can be assembled looks like this:

select t0_.id, t0_.name, t0_.age, t0_.version from Employee t0_ where t0_.id = ?

From a type-safe point of view, the point is the ʻeqmethod in thewhere (c-> c.eq (e.id, id))` that constructs the WHERE clause. This method utilizes generics to determine the type of the first argument to the type of the second argument at compile time.

In other words, in this example, the type of the second argument is determined to be the ʻInteger type by passing the property representing the ʻInteger type of the metamodel class to the first argument of the ʻeqmethod. Therefore, it prevents passing an incorrect type to the second argument (resulting in an error at runtime), for examplec.eq (e.id," String value ")`. ..

in conclusion

Using the example of getting an entity, I showed that Doma's Criteri API can be type-safe to construct SQL.

The equivalent of the code shown here is available from the project below.

Recommended Posts

Getting Started with Doma-Introduction to the Criteria API
Getting Started with Doma-Using Subqueries with the Criteria API
Getting Started with Doma-Dynamicly construct WHERE clauses with the Criteria API
Getting Started with Doma-Using Projection with the Criteira API
Getting Started with Doma-Using Joins with the Criteira API
Getting Started with Reactive Streams and the JDK 9 Flow API
Now is the time to get started with the Stream API
Getting Started with Doma-Criteria API Cheat Sheet
Getting started with the JVM's GC mechanism
Returning to the beginning, getting started with Java ② Control statements, loop statements
Getting Started with DBUnit
Getting Started with Ruby
Getting started with Kotlin to send to Java developers
Getting Started with Swift
Getting Started with Docker
Getting Started with Doma-Transactions
Getting Started with Doma-Using Logical Operators such as AND and OR in the WHERE Clause of the Criteria API
Getting Started with Doma-Annotation Processing
Getting Started with Java Collection
Getting Started with JSP & Servlet
Getting Started with Java Basics
Getting Started with Spring Boot
Getting Started with Ruby Modules
Going back to the beginning and getting started with Java ① Data types and access modifiers
What I was addicted to with the Redmine REST API
How to get started with slim
[java8] To understand the Stream API
Getting Started with Java_Chapter 5_Practice Exercises 5_4
[Google Cloud] Getting Started with Docker
Getting started with Java lambda expressions
Getting Started with Docker with VS Code
CompletableFuture Getting Started 2 (Try to make CompletableFuture)
Getting Started with Ruby for Java Engineers
I tried to get started with WebAssembly
[Note] How to get started with Rspec
Getting Started with Java Starting from 0 Part 1
How to convert an array of Strings to an array of objects with the Stream API
Getting Started with Ratpack (4)-Routing & Static Content
I tried to summarize the Stream API
Getting Started with Micronaut 2.x ~ Native Build and Deploy to AWS Lambda ~
Getting Started with Language Server Protocol with LSP4J
I want to introduce the committee with Rails without getting too dirty
Getting Started with Creating Resource Bundles with ListResoueceBundle
Part2 Part II. How to proceed with Getting Started Spring Boot Reference Guide Note ①
Print forms directly to the printer with JasperReports
Links & memos for getting started with Java (for myself)
Assignment to multiple variables with the ternary operator
Getting Started with Java 1 Putting together similar things
How to use Java API with lambda expression
pass two arguments to the URI with link_to
How to build API with GraphQL and Rails
Rails beginners tried to get started with RSpec
Try to summarize the common layout with rails
I tried Getting Started with Gradle on Heroku
I tried to check the operation of http request (Put) with Talented API Tester
Let's implement a function to limit the number of access to the API with SpringBoot + Redis
I want to hit the API with Rails on multiple docker-composes set up locally
[DDD] What is the most accessible architecture to get started with Domain Driven Design?
How to change the action with multiple submit buttons
Getting started with Java programs using Visual Studio Code
Automatically map DTOs to entities with Spring Boot API