2.アノテーションによるトランザクション

概要

Spring Transactionのアノテーションによるトランザクション制御です。

アノテーションを使用するか、宣言的トランザクションを使用するかは、ほとんど趣味の問題のような気がします。

機能的には同じです。

ですので、ここでは細かな機能を説明しません。

細かな1つ1つの機能は、宣言的トランザクションの説明を読んでください。

宣言的トランザクションを使用すれば、設定ファイル一箇所でトランザクションを管理できます。

しかし、プログラムを見たときにはどこでトランザクションが掛かっているかが分かりにくくなります。

アノテーションを使用すればプログラムを見たときにはどこでトランザクションが掛かっているか一目瞭然ですが、

逆に全体的管理が難しくなります。

このあたりは、開発の最初に決めておいた方が混乱がなくていいかと思います。

さて、では具体的に見ていきましょう。

使用サンプル

Spring設定ファイルのサンプル

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans "

xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"

xmlns:aop ="http://www.springframework.org/schema/aop "

xmlns:tx ="http://www.springframework.org/schema/tx "

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd ">

<!-- Data Source (例えばPostgres)-->

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

<property name="driverClassName" value="org.postgresql.Driver"/>

<property name="url" value="jdbc:postgresql://localhost/XXXX" />

<property name="username" value="XXX" />

<property name="password" value="XXX" />

</bean>

<!-- DAO -->

<bean id="testDao" class="dao.TestDaoImpl">

<property name="dataSource" ref="dataSource" />

</bean>

<!-- ビジネス -->

<bean id="testService" class="business.service.TestServiceImpl">

</bean>

<!-- トランザクション管理 -->

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"/>

</bean>

<!-- トランザクションのアノテーションを有効にする -->

<tx:annotation-driven />

</beans>

アノテーションを使用するためには、上記のように以下のタグを記述する必要があります。

<tx:annotation-driven />

アノテーションの記述サンプルコード

@Transactional(readOnly=true)

public class TestServiceImpl{

public find(Member member){

}

@Transactional(readOnly=false, rollbackFor=RuntimeException.class)

public update(Member member){

}

//・・・様々なメソッド

}

アノテーションは、クラスに対して記述することもできますし、メソッドに対して記述することもできます。

クラスに対して記述した設定は、メソッドで記述された設定で上書きされることに注意してください。

動作は、宣言的トランザクションと全く同じです。

アノテーションの記述方法

アノテーションの記述は、宣言的トランザクションとほぼ一緒です。

ですので、機能内容などは宣言的トランザクションの記事を読んでみてください。

ここでは、記述方法だけ大まかに書きます。

Created Date: 2011/01/31