ishowcode.eth

ishowcode.eth

区块链小白

純手書き超詳細解説Spring JdbcTemplate&宣言的トランザクション

JdbcTemplate 基本使用#

1-JdbcTemplate 基本使用 - 概述 (了解)#

JdbcTemplate は spring フレームワークで提供されるオブジェクトで、原始的で煩雑な Jdbc API オブジェクトの簡単なラッピングです。spring フレームワークは私たちに多くの操作テンプレートクラスを提供しています。例えば、関係データを操作する JdbcTemplate や HibernateTemplate、nosql データベースを操作する RedisTemplate、メッセージキューを操作する JmsTemplate などです。

2-JdbcTemplate 基本使用 - 開発ステップ (理解)#

①spring-jdbc と spring-tx の依存関係をインポート
②データベーステーブルとエンティティを作成
③JdbcTemplate オブジェクトを作成
④データベース操作を実行

3-JdbcTemplate 基本使用 - クイックスタートコード実装 (応用)#

spring-jdbc と spring-tx の依存関係をインポート#

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐test</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐jdbc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐tx</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!‐‐アスペクトパッケージ‐‐>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
<!‐‐データソース関連‐‐>
<!‐‐ Druid接続プール ‐‐>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!‐‐ mysqlドライバ ‐‐>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql‐connector‐java</artifactId>
<version>5.1.39</version>
</dependency>
<!‐‐servlet関連‐‐>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet‐api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp‐api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>

データベーステーブルとエンティティを作成

DROP TABLE IF EXISTS account;
CREATE TABLE account (
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
money DOUBLE NOT NULL
);
INSERT INTO account VALUES (NULL,'旺財',1000);
INSERT INTO account VALUES (NULL,'小強',1000);
SELECT * FROM account;
package com.summer.domain;
public class Account {
private int id;
private String name;
private double money;
public int getId() {
return id;
} 
public void setId(int id) {
this.id = id;
} 
public String getName() {
return name;
} 
public void setName(String name) {
this.name = name;
} 
public double getMoney() {
return money;
} 
public void setMoney(double money) {
this.money = money;
}
}

JdbcTemplate オブジェクトを作成
データベース操作を実行

//JdbcTemplateの開発ステップをテスト
@Test
public void test1(){
//データソースを作成
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root");
//テンプレートオブジェクトを作成
JdbcTemplate template = new JdbcTemplate();
//データソースを設定
template.setDataSource(dataSource);
//更新操作を実行 (追加、修正、削除)
int i = template.update("INSERT INTO account VALUES (NULL,?,?);", "如花", 1000);
System.out.println(i);
}

4-JdbcTemplate 基本使用 - spring によるテンプレートオブジェクトの生成分析 (理解)#

JdbcTemplate の生成権を Spring に委譲し、データソース DataSource の生成権も Spring に委譲します。Spring コンテナ内部でデータソース DataSource を JdbcTemplate テンプレートオブジェクトに注入し、Spring コンテナを通じて JdbcTemplate オブジェクトを取得して操作を実行します。

5-JdbcTemplate 基本使用 - spring によるテンプレートオブジェクトのコード実装 (応用)#

以下のように設定します:

<!‐‐データソースを設定し、データの生成をspringコンテナに委譲‐‐>
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!‐‐ jdbcテンプレートオブジェクトを作成‐‐>
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<!‐‐データソースを設定‐‐>
<property name="dataSource" ref="dataSource" />
</bean>

テストコード

//springとjunitを統合
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateTest {
@Autowired
private JdbcTemplate jdbcTemplate;
//spring管理のJdbcTemplateをテスト
@Test
public void test2(){
int i = jdbcTemplate.update("INSERT INTO account VALUES (NULL,?,?);", "秋香", 1000);
System.out.println(i);
}
}

6-JdbcTemplate 基本使用 - spring によるテンプレートオブジェクトのコード実装#

データベースの接続情報を外部設定ファイルに抽出し、spring の設定ファイルと分離することで、後のメンテナンスが容易になります。

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

設定ファイルを次のように変更します:

<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring‐beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring‐context.xsd
">
<!‐‐properties設定ファイルを読み込む‐‐>
<context:property‐placeholder location="classpath:jdbc.properties"/>
<!‐‐データソースを設定し、データの生成をspringコンテナに委譲‐‐>
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!‐‐ jdbcテンプレートオブジェクトを作成‐‐>
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<!‐‐データソースを設定‐‐>
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>

7-JdbcTemplate 基本使用 - 一般的な操作 - 更新操作 (応用)#

//springとjunitを統合
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {
//jdbcテンプレートを注入
@Autowired
private JdbcTemplate jdbcTemplate;
//更新操作をテスト
@Test
public void testUpdate(){
jdbcTemplate.update("update account set money = ? where id = ?;",800,1);
}
//削除をテスト
@Test
public void testDelete(){
jdbcTemplate.update("DELETE from account where id = ?",1);
}
}

8-JdbcTemplate 基本使用 - 一般的な操作 - クエリ操作 (応用)#

package com.summer.test;
import com.summer.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
//springとjunitを統合
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {
//jdbcテンプレートを注入
@Autowired
private JdbcTemplate jdbcTemplate;
//更新操作をテスト
@Test
public void testUpdate(){
    jdbcTemplate.update("update account set money = ? where id = ?;",800,1);
}
//削除をテスト
@Test
public void testDelete(){
jdbcTemplate.update("DELETE from account where id = ?",1);
} 
//集計クエリ
@Test
public void testQueryCount(){
Long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
System.out.println(count);
} 
//1つのクエリをテスト
@Test
public void testQueryOne(){
Account account = jdbcTemplate.queryForObject("select * from account where name=?", new
BeanPropertyRowMapper<Account>(Account.class), "旺財");
System.out.println(account);
} 
//すべてのクエリをテスト
@Test
public void testQueryAll(){
List<Account> accountList = jdbcTemplate.query("select * from account", new
BeanPropertyRowMapper<Account>(Account.class));
System.out.println(accountList);
}
}

9-JdbcTemplate 基本使用 - 知識要点 (理解、記憶)#

①spring-jdbc と spring-tx の依存関係をインポート
②データベーステーブルとエンティティを作成
③JdbcTemplate オブジェクトを作成

JdbcTemplate jdbcTemplate = newJdbcTemplate();
jdbcTemplate.setDataSource(dataSource);

④データベース操作を実行

更新操作:
jdbcTemplate.update (sql,params)
クエリ操作:
jdbcTemplate.query (sql,Mapper,params)
jdbcTemplate.queryForObject(sql,Mapper,params)

宣言型トランザクション制御#

1. トランザクションの概念#

概念:

トランザクションは一連の操作の実行単位であり、データベース操作に関しては、トランザクションは一連の SQL 命令を管理します。例えば、追加、修正、削除など、トランザクションの一貫性は、このトランザクション内の操作がすべて成功する必要があることを要求します。この過程でエラーが発生した場合、例えば 1 つの SQL 文が成功しなかった場合、この一連の操作はすべてロールバックされます。トランザクションを 4 つの言葉で説明します(ACID)
1.atomic (原子性): すべてが発生するか、すべてが発生しない。
2.consistent (一貫性): データは破壊されるべきではない。
3.Isolate (隔離性): ユーザー間の操作は混同されない。
4.Durable (持続性): 永続的に保存される、例えばデータベースに保存されるなど。

2. 注釈に基づく宣言型トランザクション制御#

2.1 宣言型トランザクション制御とは#

Spring の宣言型トランザクションは、その名の通り、宣言の方法でトランザクションを処理します。ここで言う「宣言」とは、設定ファイルで宣言することを指し、Spring 設定ファイルでの宣言型のトランザクション処理がコードによるトランザクション処理の代わりになります。

宣言型トランザクション処理の効果

  • トランザクション管理は開発コンポーネントに侵入しません。具体的には、ビジネスロジックオブジェクトはトランザクション管理が行われていることを認識しません。実際、トランザクション管理はシステムレベルのサービスであり、ビジネスロジックの一部ではありません。トランザクション管理の計画を変更したい場合は、定義ファイルで再設定するだけで済みます。
  • トランザクション管理が不要な場合は、設定ファイルを少し変更するだけでトランザクション管理サービスを削除でき、コードを変更して再コンパイルする必要がなく、メンテナンスが非常に便利です。

注意:Spring の宣言型トランザクション制御の基盤は AOP です。

aop、tx 名前空間を導入

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring‐context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring‐aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring‐tx.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring‐beans.xsd">

2.2 注釈を使用した宣言型トランザクション制御の設定#

  1. AccoutDao を作成

    @Repository("accountDao")
    public class AccountDaoImpl implements AccountDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public void out(String outMan, double money) {
    jdbcTemplate.update("update account set money=money‐? where name=?",money,outMan);
    } 
    public void in(String inMan, double money) {
    jdbcTemplate.update("update account set money=money+? where name=?",money,inMan);
    }
    }
    
    

2.AccountService を作成

@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
public void transfer(String outMan, String inMan, double money) {
accountDao.out(outMan,money);
int i = 1/0;
accountDao.in(inMan,money);
}
}
  1. applicationContext.xml 設定ファイルを作成
<!‐‐以前省略されたdatsSource、jdbcTemplate‐‐>
<!‐‐プラットフォームトランザクションマネージャ‐‐>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!‐‐トランザクションの注釈駆動‐‐>
<tx:annotation‐driven/>

2.3 注釈を使用した宣言型トランザクション制御の解析#

@Transactional を使用して、トランザクション制御が必要なクラスまたはメソッドを修飾します。注釈で使用できる属性は、xml 設定方式と同様です。例えば、隔離レベル、伝播動作など。
②注釈をクラスに使用すると、そのクラス内のすべてのメソッドが同じ注釈パラメータ設定を使用します。
③メソッドに使用すると、異なるメソッドが異なるトランザクションパラメータ設定を使用できます。
④ Xml 設定ファイルでトランザクションの注釈駆動を有効にする必要があります <tx:annotation-driven />

2.4 知識要点#

注釈による宣言型トランザクション制御の設定要点

  • トランザクション通知の設定 (@Transactional 注釈設定)

  • トランザクション注釈駆動の設定 <tx:annotation-driven/>

読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。