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

「Spring ORMの例題チュートリアルへようこそ。今日はHibernate JPAトランザクション管理を使用したSpring ORMの例題について見ていきます。以下の機能を持つ非常にシンプルなSpringスタンドアロンアプリケーションの例をご紹介します。」

  • Dependency Injection (@Autowired annotation)
  • JPA EntityManager (provided by Hibernate)
  • Annotated transactional methods (@Transactional annotation)

Spring ORMの例示

私はSpring ORMの例でインメモリデータベースを使用しているので、データベースのセットアップは必要ありません(ただし、spring.xmlのdatasourceセクションで別のデータベースに変更することもできます)。これは依存関係を最小限に抑えたSpring ORMのスタンドアロンアプリケーションです(ただし、Springに慣れれば簡単にウェブプロジェクトに変更できます)。注:@TransactionalアノテーションなしでSpring AOPベースのトランザクション処理方法を使用する場合は、このチュートリアルをご覧ください:Spring ORM AOPトランザクション管理。以下の画像は、最終的なSpring ORMの例プロジェクトを示しています。それでは、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>
  • We need spring-context and spring-orm as Spring dependencies.
  • We use hibernate-entitymanager for Hibernate as JPA implementation. hibernate-entitymanager is dependent on hibernate-core this why we don’t have to put hibernate-core in pom.xml explicitly. It’s being pulled into our project through maven transitive dependencies.
  • We also need JDBC driver as dependency for database access. We are using HSQLDB that contains the JDBC driver and a working in memory database.

スプリング ORM モデルクラス

私たちは、モデルビーンでのマッピングには標準のJPAアノテーションを使用することができます。なぜなら、Hibernateは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アノテーションを使用しています。

春のORMのDAOクラス

私たちは、永続性と検索のための非常にシンプルな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 is Spring annotation that tell the Spring container that we can use this class through Spring IoC (Dependency Injection).
  • We use JPA @PersistenceContext annotation that indicate dependency injection to an EntityManager. Spring injects a proper instance of EntityManager according to the spring.xml configuration.

スプリングのORMサービスクラス

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

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();

	}

}
  • We use Spring @Autowired annotation to inject ProductDao in our service class.
  • We want to use transaction management, so methods are annotated with @Transactional Spring annotation. The listAll method only reads the database so we set the @Transactional annotation to read-only for optimisation.

Spring ORMの例のBean設定XML

私たちのSpring ORMの例題プロジェクトのJavaクラスは準備ができていますので、今はSpringの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に対して、Springのコンポーネント(サービス、DAO)のクラスパススキャンを行い、spring xmlで個別に定義する代わりに使用することを伝えます。また、Springの注釈の検出も有効にしています。

 

    1. 次に、現在のHSQLDBインメモリデータベースのデータソースを追加します。

 

    1. アプリケーションがEntityManagerを取得するために使用するJPA EntityManagerFactoryを設定します。Springはこれを行うための3つの異なる方法をサポートしていますが、フルのJPA機能を使用するために、LocalContainerEntityManagerFactoryBeanを使用しました。LocalContainerEntityManagerFactoryBeanの属性を次のように設定します。

パッケージスキャン属性は、モデルクラスのパッケージを指すように設定します。
前述のデータソースは、springの構成ファイルで定義します。
jpaVendorAdapterはHibernateを使用し、いくつかのHibernateのプロパティを設定します。

次に、JpaTransactionManagerとしてSpringのPlatformTransactionManagerインスタンスを作成します。このトランザクションマネージャは、トランザクションデータアクセスに単一のJPA EntityManagerFactoryを使用するアプリケーションに適しています。
アノテーションに基づくトランザクション動作の構成を有効にし、作成したtransactionManagerを設定します。

スプリングORMハイバネートJPAの実例テストプログラム

私たちのSpring 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コンテナを簡単に起動できる方法がわかります。最初に依存性の注入されたエントリーポイントであるサービスクラスのインスタンスを取得しています。Springのコンテキストが初期化された後、ProductDaoクラスへの参照がProductServiceクラスに注入されます。ProducServiceのインスタンスを取得した後、そのメソッドをテストすることができます。すべてのメソッド呼び出しは、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の例プロジェクトを以下のリンクからダウンロードし、それを操作して学習することができます。

スプリングのORMとトランザクションプロジェクトをダウンロードしてください。

コメントを残す 0

Your email address will not be published. Required fields are marked *