Spring-declarative-management
春の宣言的なトランザクション管理
宣言的なトランザクション管理アプローチにより、ソースコードをハードコーディングする代わりに、設定の助けを借りてトランザクションを管理できます。 これは、ビジネスコードからトランザクション管理を分離できることを意味します。 トランザクションを管理するには、注釈またはXMLベースの構成のみを使用します。 Bean構成では、メソッドをトランザクションに指定します。 宣言型トランザクションに関連する手順は次のとおりです-
- <tx:advice/>タグを使用して、トランザクション処理アドバイスを作成し、同時に、トランザクションを作成してトランザクションアドバイスを参照するすべてのメソッドに一致するポイントカットを定義します。
- メソッド名がトランザクション構成に含まれている場合、作成されたアドバイスはメソッドを呼び出す前にトランザクションを開始します。
- ターゲットメソッドは、_try/catch_ブロックで実行されます。
- メソッドが正常に終了した場合、AOPアドバイスはトランザクションを正常にコミットします。そうでなければ、ロールバックを実行します。
上記の手順がどのように機能するかを見てみましょうが、始める前に、トランザクションを利用してさまざまなCRUD操作を実行できる少なくとも2つのデータベーステーブルを用意することが重要です。 次のDDLを使用してMySQL TESTデータベースに作成できる Student テーブルを見てみましょう-
2番目の表は*マーク*で、年に基づいて学生のマークを保持します。 ここで、 SID はStudentテーブルの外部キーです。
次に、StudentテーブルとMarksテーブルに簡単な操作を実装するSpring JDBCアプリケーションを作成しましょう。 動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。
Step | Description |
---|---|
1 | Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project. |
2 | Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. |
3 | Add other required libraries mysql-connector-java.jar, aopalliance-x.y.jar, org.springframework.jdbc.jar, and org.springframework.transaction.jar in the project. You can download required libraries if you do not have them already. |
4 | Create DAO interface StudentDAO and list down all the required methods. Though it is not required and you can directly write StudentJDBCTemplate class, but as a good practice, let’s do it. |
5 | Create other required Java classes StudentMarks, StudentMarksMapper, StudentJDBCTemplate and MainApp under the com.finddevguides package. You can create rest of the POJO classes if required. |
6 | Make sure you already created* Student and Marks *tables in TEST database. Also make sure your MySQL server is working fine and you have read/write access on the database using the given username and password. |
7 | Create Beans configuration file Beans.xml under the* src* folder. |
8 | The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below. |
以下は、データアクセスオブジェクトインターフェイスファイル StudentDAO.java の内容です。
以下は StudentMarks.java ファイルの内容です
以下は、 StudentMarksMapper.java ファイルの内容です。
定義済みのDAOインターフェイスStudentDAOの実装クラスファイル StudentJDBCTemplate.java は次のとおりです。
次に、メインアプリケーションファイル MainApp.java を使用します。これは次のとおりです。
以下は設定ファイル Beans.xml です
ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 アプリケーションで問題がなければ、次の例外が出力されます。 この場合、トランザクションはロールバックされ、データベーステーブルにレコードは作成されません。
例外を削除した後、上記の例を試すことができます。この場合、トランザクションをコミットし、データベースにレコードが表示されるはずです。