ウェブサイト検索

Spring ORMの例 - JPA、Hibernate、トランザクション


春のORM例チュートリアルへようこそ。今日は、Hibernate JPAトランザクション管理を使用したSpring ORMの例を見ていきます。次の機能を備えたSpringスタンドアロンアプリケーションの非常にシンプルな例をお見せします。

  • 依存性注入(@Autowiredアノテーション)
  • JPAエンティティマネージャー(Hibernateによって提供される)
  • 注釈付きトランザクショナルメソッド(@Transactionalアノテーション)

Spring ORMの例

Spring ORMの例ではインメモリデータベースを使用しているため、データベースのセットアップは必要ありません(ただし、spring.xmlのデータソースセクションで他のデータベースに変更することもできます)。これは依存関係を最小限に抑えたSpring ORMのスタンドアロンアプリケーションです(ただし、Springに慣れてくれば設定によって簡単にウェブプロジェクトに変更できます)。注意:Spring AOPベースのトランザクショナル(@Transactionalアノテーションなし)メソッド解決アプローチについては、こちらのチュートリアルをチェックしてください: Spring ORM AOPトランザクション管理。下の画像は私たちの最終的なSpring ORM例プロジェクトを示しています。

Spring ORM Maven 依存関係

以下は、Spring ORM 依存関係を持った最終的な pom.xml ファイルです。私たちは Spring 4 と Hibernate 4 を使用して、Spring ORM の例を作成しました。

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>hu.daniel.hari.learn.spring</groupId>
	<artifactId>Tutorial-SpringORMwithTX</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<!-- Generic properties -->
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.7</java.version>

		<!-- SPRING & HIBERNATE / JPA -->
		<spring.version>4.0.0.RELEASE</spring.version>
		<hibernate.version>4.1.9.Final</hibernate.version>

	</properties>

	<dependencies>
		<!-- LOG -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>

		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- JPA Vendor -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<!-- IN MEMORY Database and JDBC Driver -->
		<dependency>
			<groupId>hsqldb</groupId>
			<artifactId>hsqldb</artifactId>
			<version>1.8.0.7</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>
  • 私たちはSpringの依存関係としてspring-contextとspring-ormが必要です。
  • 私たちはJPA実装としてhibernate-entitymanagerをHibernateのために使用しています。hibernate-entitymanagerはhibernate-coreに依存しているため、hibernate-coreをpom.xmlに明示的に記述する必要はありません。それはMavenの伝播依存関係を通じて私たちのプロジェクトに取り込まれています。
  • データベースアクセスのためにJDBCドライバーも依存関係として必要です。私たちはJDBCドライバーと動作するインメモリデータベースを含むHSQLDBを使用しています。

Spring ORMモデルクラス

HibernateはJPAの実装を提供しているため、私たちはモデルBeanのマッピングに標準のJPAアノテーションを使用できます。

package hu.daniel.hari.learn.spring.orm.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Product {

	@Id
	private Integer id;
	private String name;

	public Product() {
	}

	public Product(Integer id, String name) {
		this.id = id;
		this.name = name;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Product [id=" + id + ", name=" + name + "]";
	}

}

私たちは、POJOをエンティティとして定義し、その主キーを定義するために、@Entityおよび@Id JPAアノテーションを使用します。

Spring ORM DAO クラス

私たちは、永続化およびfindALLメソッドを提供する非常にシンプルなDAOクラスを作成します。

package hu.daniel.hari.learn.spring.orm.dao;

import hu.daniel.hari.learn.spring.orm.model.Product;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Component;

@Component
public class ProductDao {

	@PersistenceContext
	private EntityManager em;

	public void persist(Product product) {
		em.persist(product);
	}

	public List<Product> findAll() {
		return em.createQuery("SELECT p FROM Product p").getResultList();
	}

}
  • @Componentは、SpringコンテナにこのクラスをSpring IoC(依存性注入)を通じて使用できることを知らせるSpringの注釈です。
  • 私たちは、エンティティマネージャへの依存性注入を示すために、JPAの@PersistenceContextアノテーションを使用します。Springは、spring.xmlの設定に従ってエンティティマネージャの適切なインスタンスを注入します。

Spring ORMサービスクラス

私たちのシンプルなサービスクラスには、2つの書き込みメソッド(add、addAll)と1つの読み取りメソッド(listAll)があります。

package hu.daniel.hari.learn.spring.orm.service;

import hu.daniel.hari.learn.spring.orm.dao.ProductDao;
import hu.daniel.hari.learn.spring.orm.model.Product;

import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class ProductService {

	@Autowired
	private ProductDao productDao;

	@Transactional
	public void add(Product product) {
		productDao.persist(product);
	}
	
	@Transactional
	public void addAll(Collection<Product> products) {
		for (Product product : products) {
			productDao.persist(product);
		}
	}

	@Transactional(readOnly = true)
	public List<Product> listAll() {
		return productDao.findAll();

	}

}
  • 私たちはサービスクラスにProductDaoを注入するためにSpringの@Autowiredアノテーションを使用します。
  • 私たちはトランザクション管理を使用したいので、メソッドには@TransactionalのSpringアノテーションが付けられています。listAllメソッドはデータベースを読み込むだけなので、最適化のために@Transactionalアノテーションを読み取り専用に設定しています。

Spring ORMの例のBean構成XML

私たちの春のORMの例プロジェクトのJavaクラスは準備ができました。では、次に私たちの春のBean設定ファイルを見てみましょう。spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans" 
	xmlns:p="https://www.springframework.org/schema/p"
	xmlns:context="https://www.springframework.org/schema/context" 
	xmlns:tx="https://www.springframework.org/schema/tx" 
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
		https://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		https://www.springframework.org/schema/context
		https://www.springframework.org/schema/context/spring-context-3.0.xsd
		https://www.springframework.org/schema/tx
		https://www.springframework.org/schema/tx/spring-tx.xsd
		">
	
	<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans -->
	<context:component-scan base-package="hu.daniel.hari.learn.spring" />
	<!-- Activates various annotations to be detected in bean classes e.g: @Autowired -->
	<context:annotation-config />

	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
		<property name="url" value="jdbc:hsqldb:mem://productDb" />
		<property name="username" value="sa" />
		<property name="password" value="" />
	</bean>
	
	<bean id="entityManagerFactory" 
			class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
			p:packagesToScan="hu.daniel.hari.learn.spring.orm.model"
            p:dataSource-ref="dataSource"
			>
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="generateDdl" value="true" />
				<property name="showSql" value="true" />
			</bean>
		</property>
	</bean>

	<!-- Transactions -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>
	<!-- enable the configuration of transactional behavior based on annotations -->
	<tx:annotation-driven transaction-manager="transactionManager" />

</beans>
  1. まず、Springコンポーネント(サービス、DAO)をspring.xmlに一つずつ定義するのではなく、クラスパススキャンを使用することをSpringに伝えます。また、Springのアノテーション検出も有効にしました。
  2. データソースを追加しています。現在はHSQLDBのインメモリデータベースです。
  3. 私たちは、アプリケーションがEntityManagerを取得するために使用されるJPA EntityManagerFactoryを設定しました。Springはこれを行うための3つの異なる方法をサポートしており、私たちは完全なJPA機能のためにLocalContainerEntityManagerFactoryBeanを使用しました。次のようにLocalContainerEntityManagerFactoryBeanの属性を設定しました:

    1. モデルクラスのパッケージを指す packagesToScan 属性。
    2. データソースは春の設定ファイルで以前に定義されています。
    3. jpaVendorAdapterをHibernateとして設定し、一部のHibernateプロパティを設定します。
  4. 私たちはSpringのPlatformTransactionManagerインスタンスをJpaTransactionManagerとして作成します。このトランザクションマネージャは、トランザクションデータアクセスのために単一のJPA EntityManagerFactoryを使用するアプリケーションに適しています。
  5. 私たちはアノテーションに基づいてトランザクションの動作を構成できるようにし、作成したtransactionManagerを設定します。

Spring ORM Hibernate JPA例テストプログラム

私たちの春のORM JPA Hibernateのサンプルプロジェクトが準備できたので、アプリケーションのテストプログラムを書きましょう。

public class SpringOrmMain {
	
	public static void main(String[] args) {
		
		//Create Spring application context
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:/spring.xml");
		
		//Get service from context. (service's dependency (ProductDAO) is autowired in ProductService)
		ProductService productService = ctx.getBean(ProductService.class);
		
		//Do some data operation
		
		productService.add(new Product(1, "Bulb"));
		productService.add(new Product(2, "Dijone mustard"));
		
		System.out.println("listAll: " + productService.listAll());
		
		//Test transaction rollback (duplicated key)
		
		try {
			productService.addAll(Arrays.asList(new Product(3, "Book"), new Product(4, "Soap"), new Product(1, "Computer")));
		} catch (DataAccessException dataAccessException) {
		}
		
		//Test element list after rollback
		System.out.println("listAll: " + productService.listAll());
		
		ctx.close();
		
	}
}

メインメソッドからSpringコンテナをどれほど簡単に起動できるかがわかります。サービスクラスのインスタンスという最初の依存関係が注入されたエントリーポイントを得ています。ProductDaoクラスの参照がSpringコンテキストの初期化後にProductServiceクラスに注入されます。ProductServiceインスタンスを得た後、そのメソッドをテストできます。すべてのメソッド呼び出しはSpringのプロキシメカニズムのためにトランザクショナルになります。この例ではロールバックもテストします。上記のSpring ORM例のテストプログラムを実行すると、以下のログが得られます。

Hibernate: insert into Product (name, id) values (?, ?)
Hibernate: insert into Product (name, id) values (?, ?)
Hibernate: select product0_.id as id0_, product0_.name as name0_ from Product product0_
listAll: [Product [id=1, name=Bulb], Product [id=2, name=Dijone mustard]]
Hibernate: insert into Product (name, id) values (?, ?)
Hibernate: insert into Product (name, id) values (?, ?)
Hibernate: insert into Product (name, id) values (?, ?)
Hibernate: select product0_.id as id0_, product0_.name as name0_ from Product product0_
listAll: [Product [id=1, name=Bulb], Product [id=2, name=Dijone mustard]]

2番目のトランザクションがロールバックされたため、製品リストが変更されなかったことに注意してください。添付のソースからのlog4j.propertiesファイルを使用すれば、内部で何が起こっているのかを見ることができます。参考文献: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/orm.html 最終的なSpring ORM JPA Hibernateのサンプルプロジェクトは以下のリンクからダウンロードできるので、これを使ってさらに学んでみてください。

トランザクションプロジェクトと共にSpring ORMをダウンロードする

関連記事: