1
0

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 3 years have passed since last update.

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

Last updated at Posted at 2022-04-10

まえがき

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
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?