本記事では、SpringJPA接続のサンプルを紹介し、いくつかの一般的な機能をテストするとともに、Oracleとの簡単な性能比較を行います。
依存関係の設定
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.1.RELEASE</version>
</dependency>
<!--springのその他の依存関係は、ここでは省略します。-->
設定ファイル
applicationContext.xmlファイル
内容は以下のとおりです:
<?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"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
>
<!-- IOCアノテーションスキャンを有効にする -->
<context:component-scan base-package="com.bjyada.demo" />
<!-- MVCアノテーションスキャンを有効にする -->
<mvc:annotation-driven />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<!-- 接続情報 -->
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- Connection Pooling Info -->
<property name="maxActive" value="${dbcp.maxActive}"/>
<property name="maxIdle" value="${dbcp.maxIdle}"/>
<property name="defaultAutoCommit" value="true"/>
<!-- 接続がIdle状態の場合、1時間後にタイムアウト -->
<property name="timeBetweenEvictionRunsMillis" value="3600000"/>
<property name="minEvictableIdleTimeMillis" value="3600000"/>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<property name="ignoreResourceNotFound" value="true"/>
<property name="locations">
<list>
<!-- 外部 -->
<!--<value>file:${user.dir}/dbcp.properties</value>-->
<!-- 内部 -->
<value>classpath*:dbcp.properties</value>
</list>
</property>
</bean>
<!-- Jpa Entity Managerの設定 -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
<property name="packagesToScan" value="com.bjyada.demo.entity"/>
<property name="persistenceUnitName" value="primary"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<!-- updateをnoneに変更し、Hibernateの起動ごとのテーブル作成を禁止する
自動的にデータベーステーブル構造を作成|更新|検証する
validate Hibernateをロードする際に、データベーステーブル構造を検証する
create Hibernateをロードするたびに、データベーステーブル構造を再作成する
create-drop Hibernateをロードする際に作成し、終了時にテーブル構造を削除する
update Hibernateをロードする際にデータベース構造を自動更新する-->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
</props>
</property>
</bean>
<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="${database.dialect}"/>
</bean>
<!-- トランザクションマネージャーの設定 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- アノテーショントランザクションの有効化 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Spring Data JPAスキャンディレクトリの設定 -->
<jpa:repositories base-package="com.bjyada.demo" />
<bean class="com.bjyada.demo.ExceptionHandler"></bean>
</beans>
dbcp.propertiesファイル
内容は以下のとおりです:
#OceanBaseデータベース
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://t5******.********.oceanbase.cloud:3306/test
jdbc.username=admin
jdbc.password=******
database.dialect=MYSQL
dbcp.maxIdle=5
dbcp.maxActive=40
useUnicode=true&characterEncoding=utf-8
pom.xmlファイル
内容は以下のとおりです:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>****</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<!-- その他の部分は省略 -->
application.propertiesファイル
内容は以下のとおりです(データソースとJPAの設定のみ):
spring.datasource.url=jdbc:mysql://t5******.********.oceanbase.cloud:3306/test
spring.datasource.username=admin
spring.datasource.password=******
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.Oracle12cDialect
注意
Oracleモードでは、spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle12cDialectを設定する必要があります。MySQLモードの場合は、この値をorg.hibernate.dialect.MySQL5Dialectに変更するか、この行を設定しないでください。
テストの準備
エンティティクラス
関連コードは以下のとおりです:
public class User implements Serializable {
private Integer id;
private String username;
//フレームワークを使用してテーブルを作成した後、エンティティクラスに新しい属性が追加されるとテーブルが自動的に変更されるかどうかを検証するため、一部のフィールドをコメントアウトします。
//private Date birthday;
//private String sex;
//private String address;
// ここでは、コンストラクタ、get、setメソッドを省略します。
}
データベースアクセスインターフェース
public interface UserDao extends JpaRepository<User,Serializable>{
User findById(Integer id);
}
サンプルコード
自動テーブル作成
テスト方法:
@Test
public void testInsert(){
User user = new User();
user.setId(1);
user.setUsername("テストデータ");
userDao.save(user);
}
実行結果:
obclient> drop table user;
Query OK, 0 rows affected
obclient› select * from user;
+----+-------------+
| id | username |
+----+-------------+
| 1 | テストデータ |
+----+-------------+
1 row in set
テーブルの変更(フィールドの追加)
Userクラスでコメントアウトされているプロパティを解除し、以下のメソッドを実行します。
@Test
public void testAlert(){
User user = new User();
user.setId(1);
user.setUsername("テストデータ");
user.setAddress("北京");
user.setSex("男");
user.setBirthday(new Date());
userDao.save(user);
}
実行結果:
obclient› select * from user;
+----+-------------+
| id | username |
+----+-------------+
| 1 | テストデータ |
+----+-------------+
1 row in set
obclient› select * from user;
+----+-------------+---------+----------------------+------+
| id | username | address | birthday | sex |
+----+-------------+---------+----------------------+------+
| 1 | テストデータ | NULL | NULL | NULL |
| 2 | テストデータ | 北京 | 2020-09-18 18:23:55 | 男 |
+----+-------------+---------+----------------------+------+
テストの結果、OceanBaseはSpringJPAのAlert Table機能を良好にサポートしています。
データの永続化
テスト方法:
@Test
public void testInsert(){
List<User> list = new ArrayList<User>();
list.add(new User(3,"asd", new Date(), "男", "漳州"));
list.add(new User(4,"qwe", new Date(), "女", "杭州"));
list.add(new User(5,"zxc", new Date(), "男", "上海"));
list.add(new User(6,"xcv", new Date(), "女", "杭州"));
list.add(new User(7,"sdf", new Date(), "男", "杭州"));
list.add(new User(8,"wer", new Date(), "女", "杭州"));
list.add(new User(9,"ert", new Date(), "男", "漳州"));
list.add(new User(10,"rty", new Date(), "女", "上海"));
list.add(new User(11,"tyu", new Date(), "男", "杭州"));
list.forEach(s -> userDao.save(s));
}
実行結果:
+----+----------+---------+---------------------+-----+
| id | username | address | birthday | sex |
+----+----------+---------+---------------------+-----+
| 1 | テストデータ | NULL | NULL | NULL|
| 2 | テストデータ | 北京 | 2020-09-18 18:23:55 | 男 |
| 3 | asd | 漳州 | 2020-09-18 18:31:35 | 男 |
| 4 | qwe | 杭州 | 2020-09-18 18:31:35 | 女 |
| 5 | zxc | 上海 | 2020-09-18 18:31:35 | 男 |
| 6 | xcv | 杭州 | 2020-09-18 18:31:35 | 女 |
| 7 | sdf | 杭州 | 2020-09-18 18:31:35 | 男 |
| 8 | wer | 杭州 | 2020-09-18 18:31:35 | 女 |
| 9 | ert | 漳州 | 2020-09-18 18:31:35 | 男 |
| 10 | rty | 上海 | 2020-09-18 18:31:35 | 女 |
| 11 | tyu | 杭州 | 2020-09-18 18:31:35 | 男 |
+----+----------+---------+---------------------+-----+
テストの結果、OceanBaseはSpringJPAのInsert機能をサポートしていることが確認されました。
主キーによるクエリ
テスト方法:
@Test
public void testFindOne(){
Table_Test one = table_testDao.findOne("aaa");
System.out.println(one);
}
実行結果:
@Test
public void test2(){
Table_Test one = table_testDao. findOne(id: "aaa");
System.out.println(one);
}
✔️ Tests passed: 1 of 1 test - 87 ms
Table_Test {char_test='aaa', varchar2_test='aaa', nchar_ test=' aaa'
Process finished with exit code 0
テストの結果、OceanBaseはSpringJPAのfindOne機能をサポートしていることが確認されました。
主キーまたはオブジェクトによるレコードの削除
テスト方法:
@Test
public void testDelete(){
table_testDao.delete("9998");
}
@Test
public void test6(){
Table_Test a = new Table_Test();
a.setChar_test("9997");
table_testDao.delete(a);
}
実行結果:
| 9996 | aaa | aaa | 21-SEP-20 | 010203 |
| 9999 | NULL | NULL | NULL | NULL |
テストの結果、OceanBaseはSpringJPAのdelete機能をサポートしていることが確認されました。
レコードの更新
テスト方法:
@Test
public void testChange(){
Table_Test one = table_testDao.findOne("9996");
System.out.println("変更前:"+one);
one.setVarchar2_test("変更済み");
one.setNchar_test("変更済み");
table_testDao.save(one);
one = table_testDao.findOne("9996");
System.out.println("変更後:"+one);
}
実行結果:
@Test
public void test3(){}
Table_Test one = table_testDao. findone(id: "9996");
System.out.println("変更前:"+one):
one.setVarchar2_test("変更済み"):
one.setNchar_tes("変更済み");
table_testbao, save(one);
one = table_testDao. findOne(id: "9996");
System.out.println("変更後: "+one);
}
✔️ Tests passed: 1 of 1 test - 187 ms
変更前: Table_Test{char_test='9996', varchar2_test='aaa', nchar_test='aaa
変更後: Table_Test{char_test='9996', varchar2_test='変更済み', nchar_test='変更済み'
Process finished with exit code 0
テストの結果、OceanBaseはSpringJPAのデータ変更機能を良好にサポートしていることが確認されました。
フルテーブルクエリ
テスト方法:
@Test
public void testFindAll(){
List<User> all = userDao.findAll();
all.forEach(System.out::println);
}
実行結果:
@Test
public void testFindAll(){
List<User> all = userDao.findAllO;
all.forEach(System.out::println);
}
✔️ Tests passed: 1 of 1 test - 235 ms
INFO: HHH000232: Schema update complete
User{id=1, username='テストデータ', birthday=null, sex='null', address='null'}
User{id=2, username='テストデータ', birthday=2020-09-18 18:23:55.0, sex='男, 'address='北京'}
User{id=3, username='asd', birthday=2020-09-18 18:31:35.0, sex='男', address='漳州'}
User{id=4, username='qwe', birthday=2020-09-18 18:31:35.0, sex='女', address='杭州'}
User{id=5, username='zxc', birthday=2020-09-18 18:31:35.0, sex='男', address='上海"}
User{id=6, username='xcv', birthday=2020-09-18 18:31:35.0, sex='女', address='杭州'}
User{id=7, username='sdf', birthday=2020-09-18 18:31:35.0, sex='男, address='杭州'}
Useriid=8, username='wer', birthday=2020-09-18 18:31:35.0, sex='女', address='杭州'}
User{id=9, username='ert', birthday=2020-09-18 18:31:35.0,sex='男, address='漳州'}
User{id=10, username='rty', birthday=2020-09-18 18:31:35.0, sex='男', address='上海'}
User{id=11, username='tyu', birthday=2020-09-18 18:31:35.0, sex='男', address='杭州'}
テストの結果、OceanBaseはSpringJPAのFindAll機能を良好にサポートしています。