LoginSignup
0

posted at

updated at

【Java】HibernateでEntity/DB間をマッピングする仕組み

まえがき

Entityクラスに@Table,@EntityをつけてORMをなんとなくで実現していたが、その仕組みをちゃんと知ろうという記事。

2つのNaming Strategy

・Entityクラス と DB 間で「テーブル名」「カラム名」のマッピングを行う際にNaming Strategyを利用する。
・Naming Strategyは「Explicit Strategy」と「Imlicit Strategy」の2つ存在する。
・マッピング処理は次のフローで行われる。

 ① LogicalNameの決定【Implicit Strategy】
 ② PhysicalNameの決定【Explicit Strategy】

  LogicalName:Javaで扱うテーブル名,プロパティ名
  PhysicalName:DBとマッピングさせるテーブル名,プロパティ名

① LogicalNameの決定【Implicit Strategy】

・デフォルトのImplicit Strategy(ImplicitNamingStrategyJpaCompliantImpl)の場合、Javaクラスで定義されているテーブル名、プロパティ名をそのままLogicalNameとする。
・そうしたくない場合/自分でLogicalNameを設定したい場合は、@Table,@Columnで設定する。

@Entity
@Table(name = "Customers")
public class Customer {

    @Id
    @GeneratedValue
    private Long id;

    private String firstName;

    private String lastName;

    @Column(name = "email")
    private String emailAddress;
    
    // getters and setters
    
}

↑のCustomerクラスのLogicalNameは以下のようになる。

Customer -> Customers
firstName -> firstName
lastName -> lastName
emailAddress -> email

② PhysicalNameの決定【Explicit Strategy】

・Hibernate5デフォルトのExplicit Strategyは、PhysicalNamingStrategyStandardImplクラス。
・LogicalNameをそのままPhysicalNameとして利用してくれる。

・Hibernate4デフォルトのExplicit StrategyはSpringPhysicalNamingStrategyクラス。
・テーブル名は一律小文字に変換されたり、ドット→アンダースコア変換等の処理が走るもの。

・LogicalNameをそのままPhysicalNameとして使ってくれる方がいいよね、ってことでHibernete5のPhysicalNamingStrategyStandardImplクラスを使うのが良い👍

application.propertiesで設定可能

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

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
What you can do with signing up
0