全部產品
Search
文件中心

ApsaraDB for OceanBase:SpringJPA 串連 OceanBase 資料庫

更新時間:Jul 01, 2024

本文介紹 SpringJPA 串連樣本,並測試幾個常用功能,與 MySQL 進行簡單的效能對比。

配置依賴

<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一個小時後逾時 -->
        <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>

    <!-- 啟用 annotation事務 -->
    <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://xxx.xxx.xxx.xxx:3306/test
jdbc.username=a****
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://xxx.xxx.xxx.xxx:3306/test
spring.datasource.username=a****
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.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);
}

執行結果:

1

修改表(增加欄位)

開啟 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);
}

執行結果:

2

經測試,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));
}

執行結果:

3

經測試,OceanBase 對於 SpringJPA 的 Insert 功能支援良好。

根據主鍵查詢

測試方法:

@Test
public void testFindOne(){
    Table_Test one = table_testDao.findOne("aaa");
    System.out.println(one);
}

執行結果:

4

經測試,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);
}

執行結果:

5

經測試,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);
}

執行結果:

6

經測試,OceanBase 對於 SpringJPA 的修改資料功能支援良好。

全表查詢

測試方法:

@Test
public void testFindAll(){
    List<User> all = userDao.findAll();
    all.forEach(System.out::println);
}

執行結果:

7

經測試,OceanBase 對於 SpringJPA 的 FindAll 功能支援良好。