全部產品
Search
文件中心

Tablestore:通過Hibernate使用SQL查詢

更新時間:Jun 06, 2026

通過Table Store JDBC 驅動整合 Hibernate ORM 架構,可在 Java 應用中以 ORM 方式查詢Table Store資料。

前提條件

  • 已擷取 AccessKey。RAM 使用者需具備 "Action": "ots:SQL*" 許可權。

  • 已建立資料表和映射表,詳見DDL 操作。

使用流程

步驟一:安裝JDBC驅動

可通過以下兩種方式安裝 JDBC 驅動。

添加Maven依賴

在 Maven 工程的 pom.xml 中添加Table Store JDBC 驅動依賴。以 5.17.0 版本為例,在 <dependencies> 內加入如下內容:

<dependency>
  <groupId>com.aliyun.openservices</groupId>
  <artifactId>tablestore-jdbc</artifactId>
  <version>5.17.0</version>
</dependency>

手動安裝

下載 Table Store JDBC 驅動並匯入到專案中。

步驟二:安裝Hibernate

可通過以下兩種方式安裝 Hibernate。

添加Maven依賴

在 Maven 工程的 pom.xml 中添加 Hibernate 依賴。以 3.6.3.Final 版本為例,在 <dependencies> 內加入如下內容:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>3.6.3.Final</version>
</dependency>

手動安裝

下載 Hibernate 安裝包並匯入到專案中。

步驟三:映射SQL欄位

建立資料表欄位對應的 Java Bean,並通過映射設定檔將 Bean 成員變數與資料表欄位一一映射。

  1. 建立資料表欄位對應的 Java Bean。

    package hibernate;
    
    public class Trip {
    
        private long tripId;
        private long duration;
        private String startDate;
        private String endDate;
        private long startStationNumber;
        private long endStationNumber;
        private String startStation;
        private String endStation;
        private String bikeNumber;
        private String memberType;
        
        // 以 tripId 為例,其他欄位類似。
        public void setTripId(Long tripId){
            this.tripId = tripId;
        }
        public Long getTripId() {
            return tripId;
        }
    }
  2. 建立映射設定檔。以在 hibernate 目錄下建立 Trip.hbm.xml 為例,將 Java Bean 的成員變數與資料表欄位對應。

    重要

    如果僅查詢資料而不寫入,建議將屬性列的 insert 和 update 屬性設為 false,避免 Hibernate 自動產生寫入語句。SQL 資料類型映射規則參見 SQL資料類型映射。

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC
            "-//Hibernate/Hibernate Mapping DTD//EN"
            "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <!--此處的類名必須與實際類名稱一致。-->
        <class name="hibernate.Trip" table="trips">
            <!-- id元素中配置的欄位為資料表中的主鍵列。-->
            <id name="tripId" column="trip_id" type="long"/>
            <!-- 如果僅查詢資料,建議將屬性列的 insert 和 update 設定為 false。-->
            <property name="duration" column="duration" type="long" insert="false" update="false"/>
            <property name="startDate" column="start_date" type="string" insert="false" update="false"/>
            <property name="endDate" column="end_date" type="string" insert="false" update="false"/>
            <property name="startStationNumber" column="start_station_number" type="long" insert="false" update="false"/>
            <property name="endStationNumber" column="end_station_number" type="long" insert="false" update="false"/>
            <property name="startStation" column="start_station" type="string" insert="false" update="false"/>
            <property name="endStation" column="end_station" type="string" insert="false" update="false"/>
            <property name="bikeNumber" column="bike_number" type="string" insert="false" update="false"/>
            <property name="memberType" column="member_type" type="string" insert="false" update="false"/>
        </class>
    </hibernate-mapping>

步驟四:構建SessionFactory

完成設定檔設定後,載入 Hibernate 設定檔建立 SessionFactory。

  1. 建立 Hibernate 設定檔 hibernate.cfg.xml 並添加以下內容,根據實際情況修改配置項。

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
        <session-factory>
            <property name="hibernate.connection.driver_class">com.alicloud.openservices.tablestore.jdbc.OTSDriver</property>
            <property name="hibernate.connection.url">jdbc:ots:https://myinstance.cn-hangzhou.ots.aliyuncs.com/myinstance</property>
            <property name="hibernate.connection.username">************************</property>
            <property name="hibernate.connection.password">********************************</property>
            <property name="hibernate.connection.autocommit">true</property>
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
            <!-- 設定為映射設定檔的路徑。-->
            <mapping resource="hibernate/Trip.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>

    配置項說明如下。

    配置項

    類型

    是否必選

    描述

    hibernate.connection.driver_class

    class

    是

    Table Store JDBC 驅動的類名,固定為 com.alicloud.openservices.tablestore.jdbc.OTSDriver。

    hibernate.connection.url

    string

    是

    執行個體訪問地址,格式為 jdbc:ots:endpoint/instanceName。其中 endpoint 為執行個體的服務地址,instanceName 為執行個體名稱,根據實際情況修改。

    hibernate.connection.username

    string

    是

    阿里雲帳號或 RAM 使用者的 AccessKey ID。

    hibernate.connection.password

    string

    是

    阿里雲帳號或 RAM 使用者的 AccessKey Secret。

    hibernate.connection.autocommit

    boolean

    是

    是否自動認可。

    重要

    Table Store不支援事務,autocommit 必須設為 true。

    hibernate.dialect

    string

    是

    Table Store SQL 相容 MySQL 文法,固定為 org.hibernate.dialect.MySQLDialect。

  2. 載入 Hibernate 設定檔構建 SessionFactory。

    SessionFactory factory = new Configuration().
      configure("hibernate/hibernate.cfg.xml").
      buildSessionFactory();

步驟五:建立Session查詢資料

通過 SessionFactory 建立 Session,調用 get 方法按主鍵查詢資料。

Session session = factory.openSession();
Trip trip = (Trip) session.get(Trip.class, 99L); 
System.out.println("trip id: " + trip.getTripId());
System.out.println("start date: " + trip.getStartDate());
System.out.println("end date: " + trip.getEndDate());
System.out.println("duration: " + trip.getDuration());
session.close();
factory.close();

完整樣本

查詢表中指定主鍵行並擷取列值。以主鍵列值 99 為例:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import hibernate.Trip;

public class HibernateDemo {
    public static void main(String[] args) {
        SessionFactory factory = new Configuration().
                configure("hibernate/hibernate.cfg.xml").
                buildSessionFactory();
        Session session = factory.openSession();
        Trip trip = (Trip) session.get(Trip.class, 99L);
        System.out.println("trip id: " + trip.getTripId());
        System.out.println("start date: " + trip.getStartDate());
        System.out.println("end date: " + trip.getEndDate());
        System.out.println("duration: " + trip.getDuration());
        session.close();
        factory.close();
    }
}           

常見問題

Unable to instantiate default tuplizer

報錯資訊:

org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

原因:缺少 javassist 依賴。

解決方案:

在 pom.xml 中添加:

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.15.0-GA</version>
</dependency>

Unknown column '{columnName}' in 'field list'

原因:SQL 映射表中不存在指定列。

解決方案:

  • 在預定義列中添加指定列,該列會自動同步到 SQL 映射表中。

  • 通過 CREATE TABLE 或 ALTER TABLE 語句在映射表中添加指定列,詳見DDL 操作。