0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JPAでの楽観ロック

Last updated at Posted at 2022-10-04

JPA(Java Persistence API)を利用した楽観ロックを実装します。

■検証環境

・openjdk version "11.0.7" 2020-04-14 LTS
・Spring Boot 2.7.3
・Spring Data Jpa 2.7.0
・lombok 1.18.24
・mysql-connector-java 8.0.30
・MySQL 8.0.30

■MySQLのテーブルデータ

PRODUCT_TBL

ID Product Price
001 Orenge 200
002 Apple 150
0033 Pineappl 200

1.テーブルにVesionカラムを追加

mysql> ALTER TABLE PRODUCT_TBL ADD Version long;
mysql> select * from PRODUCT_TBL;
+--------+----------------+---------+---------+
| ID     | Product        | Price   | version |
+--------+----------------+---------+---------+
| 001    | Orenge         |     200 |       0 |
| 002    | Apple          |     150 |       0 |
| 003    | Pineappl       |     200 |       0 |
+--------+----------------+---------+---------+

2.エンティティクラスを作成

バージョンを管理するカラムに@Versionアノテーションを付与する。

ProductEntity.java
@Entity
@Table(name="PRODUCT_TBL")
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Product {
    @Id
    private String id;
    private String product;
    private int price;
    @Version
    private long version;
}

3.リポジトリインターフェースを作成

ProductRepository.java
@Repository
public interface ProductRepository extends JpaRepository<Product, String> {
}

5.検証

5.1.コントローラークラスを用意し更新処理を行う。

テーブルのバージョンカラムが更新する毎にカウントアップされる事を確認。
注意事項として項目に変更がない場合、カウントアップはされない。

5.2.楽観ロックに失敗した場合、次の例外が発生する。
exception is org.springframework.orm.ObjectOptimisticLockingFailureException
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?