Hibernate EntityManagerのガイド

Hibernate EntityManagerのガイド

1. 前書き

EntityManagerは、Java PersistenceAPIの一部です。 主に、JPA2.0仕様で定義されているプログラミングインターフェイスとライフサイクルルールを実装します。

さらに、EntityManagerのAPIを使用して、永続コンテキストにアクセスできます。

このチュートリアルでは、EntityManagerの構成、タイプ、およびさまざまなAPIを確認します。

2. Mavenの依存関係

まず、Hibernateの依存関係を含める必要があります。


    org.hibernate
    hibernate-core
    5.4.0.Final

使用しているデータベースに応じて、ドライバーの依存関係も含める必要があります。


    mysql
    mysql-connector-java
    8.0.13

hibernate-coreおよびmysql-connector-javaの依存関係は、MavenCentralで利用できます。

3. 設定

次に、データベース内のMOVIEテーブルに対応するMovieエンティティを使用して、EntityManagerを示します。

この記事では、EntityManager APIを使用して、データベース内のMovieオブジェクトを操作します。

3.1. エンティティの定義

@Entityアノテーションを使用して、MOVIEテーブルに対応するエンティティを作成することから始めましょう。

@Entity
@Table(name = "MOVIE")
public class Movie {

    @Id
    private Long id;

    private String movieName;

    private Integer releaseYear;

    private String language;

    // standard constructor, getters, setters
}

3.2. persistence.xmlファイル

EntityManagerFactoryが作成されると、the persistence implementation searches for the META-INF/persistence.xml file in the classpathになります。

このファイルには、EntityManagerの構成が含まれています。


    Hibernate EntityManager Demo
    com.example.hibernate.pojo.Movie
    true
    
        
        
        
        
        
        
    

説明するために、EntityManagerによって管理される基礎となるデータストアを指定するpersistence-unitを定義します。

さらに、基礎となるデータストアの方言と他のJDBCプロパティを定義します。 Hibernateはデータベースに依存しません。 Based on these properties, Hibernate connects with the underlying database.

4. コンテナおよびアプリケーション管理EntityManager

基本的に、there are two types of EntityManager – Container Managed and Application Managed.

それぞれのタイプを詳しく見ていきましょう。

4.1. コンテナ管理EntityManager

ここで、コンテナはエンタープライズコンポーネントにEntityManagerを挿入します。

言い換えると、コンテナはEntityManagerFactoryからEntityManagerを作成します。

@PersistenceContext
EntityManager entityManager;

これは、the container is in charge of beginning, committing, or rolling back the transaction.も意味します

4.2. アプリケーション管理EntityManager

逆に、EntityManagerのライフサイクルは、ここのアプリケーションによって管理されます。

実際、EntityManager.を手動で作成します。さらに、作成したEntityManagerのライフサイクルも管理します。

まず、EntityManagerFactory:を作成しましょう

EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.example.movie_catalog");

EntityManagerを作成するには、EntityManagerFactorycreateEntityManager()を明示的に呼び出す必要があります。

public static EntityManager getEntityManager() {
    return emf.createEntityManager();
}

5. Hibernateエンティティの操作

EntityManager APIは、メソッドのコレクションを提供します。 これらのメソッドを使用して、データベースと対話できます。

5.1. 永続化エンティティ

オブジェクトをEntityManagerに関連付けるために、persist()メソッドを使用できます。

public void saveMovie() {
    EntityManager em = getEntityManager();

    em.getTransaction().begin();

    Movie movie = new Movie();
    movie.setId(1L);
    movie.setMovieName("The Godfather");
    movie.setReleaseYear(1972);
    movie.setLanguage("English");

    em.persist(movie);
    em.getTransaction().commit();
}

オブジェクトがデータベースに保存されると、persistent状態になります。

5.2. エンティティの読み込み

データベースからオブジェクトを取得するために、find()メソッドを使用できます。

ここでは、メソッドは主キーで検索します。 実際、メソッドはエンティティクラスタイプと主キーを想定しています。

public Movie getMovie(Long movieId) {
    EntityManager em = getEntityManager();
    Movie movie = em.find(Movie.class, new Long(movieId));
    em.detach(movie);
    return movie;
}

代わりにHowever, if we just need the reference to the entity, we can use the getReference()メソッド。 実際には、エンティティにプロキシを返します。

Movie movieRef = em.getReference(Movie.class, new Long(movieId));

5.3. エンティティの切り離し

永続コンテキストからエンティティを切り離す必要がある場合は、we can use the detach() method。 メソッドにパラメーターとしてデタッチするオブジェクトを渡します。

em.detach(movie);

エンティティが永続コンテキストから切り離されると、エンティティは切り離された状態になります。

5.4. エンティティのマージ

実際には、多くのアプリケーションでは、複数のトランザクションにわたるエンティティの変更が必要です。 たとえば、UIにレンダリングするために1つのトランザクションでエンティティを取得する場合があります。 次に、別のトランザクションがUIで行われた変更を取り込みます。

このような状況では、merge()メソッドを利用できます。 The merge method helps to bring in the modifications made to the detached entity, in the managed entity, if any:

public void mergeMovie() {
    EntityManager em = getEntityManager();
    Movie movie = getMovie(1L);
    em.detach(movie);
    movie.setLanguage("Italian");
    em.getTransaction().begin();
    em.merge(movie);
    em.getTransaction().commit();
}

5.5. エンティティのクエリ

さらに、JPQLを使用してエンティティを照会できます。 getResultList()を呼び出して実行します。

もちろん、クエリが単一のオブジェクトのみを返す場合は、getSingleResult(),を使用できます。

public List queryForMovies() {
    EntityManager em = getEntityManager();
    List movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1")
      .setParameter(1, "English")
      .getResultList();
    return movies;
}

5.6. エンティティの削除

さらに、we can remove an entity from the database using the remove() method。 オブジェクトはデタッチされませんが、削除されることに注意してください。

ここで、エンティティの状態は永続から新規に変わります。

public void removeMovie() {
    EntityManager em = HibernateOperations.getEntityManager();
    em.getTransaction().begin();
    Movie movie = em.find(Movie.class, new Long(1L));
    em.remove(movie);
    em.getTransaction().commit();
}

6. 結論

この記事では、HibernateEntityManagerについて説明しました。 タイプと構成を確認し、persistence context.を操作するためにAPIで使用できるさまざまなメソッドについて学習しました。

いつものように、この記事で使用されているコードはover at Githubで利用できます。