iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐧

Using Text Blocks and Records with MyBatis

に公開
2022/07/09

Java 15 introduced Text Blocks, Java 16 introduced Records, and the recently released MyBatis 3.5.10 now supports Records.

Since the environment is now ready to use Text Blocks and Records with MyBatis, I will try them out.

The code used this time can be found in the following project:

Environment Information

  • Java 17
  • Spring Boot 2.6.8
  • DB: H2 Database

I used a table like the following:

CREATE TABLE customers (
	id INT PRIMARY KEY AUTO_INCREMENT,
	first_name VARCHAR(30) NOT NULL,
	last_name VARCHAR(30) NOT NULL,
	address VARCHAR(100)
);

Usage

Using MyBatis 3.5.10

If you are explicitly specifying the MyBatis dependency, you simply need to change the version to 3.5.10. However, if you are using mybatis-spring-boot-starter with Spring Boot, the current version 2.2.2 uses MyBatis 3.5.9, so you will need to add a specific dependency for MyBatis itself.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.flywaydb:flyway-core'
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.2'
+   implementation 'org.mybatis:mybatis:3.5.10'
    runtimeOnly 'com.h2database:h2'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

Entity

Define the entity class as a record.

package com.example.domain;

public record Customer(Integer id, String firstName, String lastName, String address) {
}

Mapper

SQL is written with annotations in the Mapper, and this is where we use Text Blocks.

However, because we are using Records, useGeneratedKeys is no longer available. This resulted in some tedious code where I had to use H2 Database's SCOPE_IDENTITY to fetch the record in order to get the ID issued by AUTO_INCREMENT. I'll go into more detail about this later.

package com.example.repository;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import com.example.domain.Customer;

@Repository
@Mapper
public interface CustomerRepository {

    @Select("""
SELECT
  *
FROM
  customers
ORDER BY
  id
    """)
    public List<Customer> findAll();

    @Select("""
SELECT
  *
FROM
  customers
WHERE
  id = #{id}
    """)
    public Customer findOne(@Param("id") int id);

    @Insert("""
INSERT INTO customers(
  first_name
  , last_name
  , address
)
VALUES(
  #{firstName}
  , #{lastName}
  , #{address}
)
""")
    public void insert(Customer customer);

    @Select("""
SELECT
  *
FROM
  customers
WHERE
  id = SCOPE_IDENTITY()
    """)
    public Customer findLast();

    @Update("""
UPDATE customers
  SET
    first_name = #{customer.firstName}
    , last_name = #{customer.lastName}
    , address = #{customer.address}
WHERE
  id = #{id}
""")
    public void update(@Param("id") int id, @Param("customer") Customer customer);

    @Delete("""
DELETE FROM customers
WHERE
  id = #{id}
    """)
    public void delete(@Param("id") Integer id);

    @Select("""
SELECT
  *
FROM
  customers
WHERE
  first_name LIKE '%' || #{firstName} || '%'
ORDER BY
  id
    """)
    public List<Customer> findByFirstName(@Param("firstName") String firstName);

    @Delete("""
DELETE FROM customers
    """)
    public void deleteAll();
}

Actual Experience

Text Blocks

Thanks to Text Blocks, it has become much easier to write SQL within annotations.
I used to write Mappers in Groovy just to be able to write multi-line strings, but now I can do it in Java.

While there is also the option of writing SQL in separate files, I personally believe it's easier to understand when the code and SQL are kept close together, so this is very helpful.

Records

I feel that using Records as entities is a bit of a mixed bag.

Since Records are immutable, you cannot use useGeneratedKeys to set the generated ID.
This is because useGeneratedKeys works by setting values on the object passed as an argument. Using useGeneratedKeys with a Record results in an error because the values cannot be modified.
In this instance, it turned into quite a tedious process of having to execute a separate SQL query to retrieve the inserted record.

Incidentally, if you are using a database that supports RETURNING like PostgreSQL, you can avoid this by returning the record using RETURNING. (I usually use PostgreSQL, so I'm in the "RETURNING camp" rather than using useGeneratedKeys.)

    @Select("""
INSERT INTO customers(
  first_name
  , last_name
  , address
)
VALUES(
  #{firstName}
  , #{lastName}
  , #{address}
)
RETURNING *
"""
)
    public Customer insert(Customer customer);

Also, as the number of fields in a Record grows, the number of constructor arguments becomes difficult to manage, so a Builder-like pattern might be necessary to use them effectively as entities.

There seem to be various situations where immutability can be problematic. Regardless of this specific case, I personally think I might not use Records that aggressively... (perhaps only for simple cases with few fields or when using them like tuples?)

Discussion