本节主要介绍如何使用 Hibernate 框架连接 TDSQL PG 数据库,实现数据的增删查改等基本操作。
简介
Hibernate 是一个开放源代码的对象关系映射框架,它对 JDBC 进行了非常轻量级的对象封装,它将 POJO 与数据库表建立映射关系,是一个全自动的 ORM 框架,Hibernate 可以自动生成 SQL 语句,自动执行,使得 Java 程序员可以随心所欲的使用对象编程思维来操纵数据库。
引入和配置 Hibernate 框架
前置依赖
在配置之前需要保证你的机器上已安装对应版本的 JDK,本例是 JDK 8。
驱动名
com.tencentcloud.tdsql.pg.jdbc.Driver
连接 URL(Oracle 模式下需打开 oracle_compile 参数)
jdbc:tdsql-pg://host:port/database?oracle_compile=true
创建 Maven 项目
创建 Maven 项目,如下:


注意:
本文档示例项目使用的 IDE 是 IntelliJ IDEA 2022.3 (Ultimate Edition),也可根据喜好选择合适的 IDE。
配置 pom.xml 文件,导入项目依赖
配置文件
pom.xml
如下,配置 dependencies 部分。<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.tencentcloud.tdsql</groupId><artifactId>TDSQL_PG_Hibernate</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><!-- orm框架Hibernate --><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>5.6.15.Final</version></dependency><!-- 测试框架Junit5 --><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-engine</artifactId><version>5.10.0</version><scope>test</scope></dependency><!-- TDSQL-PG JDBC驱动 --><dependency><groupId>com.tencentcloud.tdsql</groupId><artifactId>tdsql-pg-connector-java8</artifactId><version>1.1.0</version><scope>system</scope><systemPath>${project.basedir}/lib/tdsql-pg-connector-java8-1.1.0.jar</systemPath></dependency></dependencies></project>
通过
<dependencies>
定义项目所依赖的组件,主要包括:1. Hibernate 依赖包,填写好后会从公共库自动下载。
2. JUnit5 测试框架依赖包,填写好后会从公共库自动下载。
3. 下载 TDSQL-PG JDBC 驱动包,并在
TDSQL_PG_Hibernate
目录下新建lib
目录,将驱动包拷贝到lib
目录下。配置 Hibernate
在
TDSQL_PG_Hibernate/src/main/resources
目录下新建 hibernate.cfg.xml
文件,用于配置 Hibernate,hibernate.cfg.xml
配置如下:<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- 配置JDBC连接信息:host、port、database、user、password 需要替换为数据库管理员提供的数据库相关信息。 --><property name="hibernate.connection.driver_class">com.tencentcloud.tdsql.pg.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:tdsql-pg://host:port/database?oracle_compile=true</property><property name="hibernate.connection.username">user</property><property name="hibernate.connection.password">password</property><!-- 配置数据库方言 --><property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL10Dialect</property></session-factory></hibernate-configuration>
其中,需要配置 JDBC 连接信息和数据库方言:
hibernate.connection.driver_class
:指定驱动包名为com.tencentcloud.tdsql.pg.jdbc.Driver
。hibernate.connection.url
:指定连接 URL,包括数据库地址、端口、数据库名、连接属性等信息。hibernate.connection.username
:指定用户名。hibernate.connection.password
:指定相应用户的密码。hibernate.dialect
:指定数据库方言为 PostgreSQL 的数据库方言,使 Hibernate 生成适当的 SQL。至此,已完成 Hibernate 项目的基本配置,完整的项目目录结构如下图所示:


开发示例
添加数据表对应的实体类
首先,开发使用的数据表为
STUDENT
表(CREATE TABLE STUDENT(ID INT PRIMARY KEY, NAME VARCHAR(50))
),对应地添加实体类Student
,先在 TDSQL_PG_Hibernate/src/main/java/
下创建 Package: com.tencentcloud.tdsql.pojo
再在TDSQL_PG_Hibernate/src/main/java/com/tencentcloud/tdsql/pojo
目录下新建 Student.java
文件:package com.tencentcloud.tdsql.pojo;public class Student {private int id;private String name;public Student() {}public Student(int id, String name) {this.id = id;this.name = name;}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;}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + "]";}}
配置实体类与数据表之间的映射
其次,需要将 Java 对象
Student
映射到数据库中的表 STUDENT
,先在 TDSQL_PG_Hibernate/src/main/resources/
下创建文件夹: com/tencentcloud/tdsql/pojo
在TDSQL_PG_Hibernate/src/main/resources/com/tencentcloud/tdsql/pojo
下新建 Student.hbm.xml
映射文件,如下:<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.tencentcloud.tdsql.pojo"><!-- 配置表和属性 --><class name="Student" table="STUDENT"><id name="id" column="ID" type="java.lang.Integer"><generator class="org.hibernate.id.Assigned" /></id><property name="name" column="NAME" length="50" type="java.lang.String"/></class></hibernate-mapping>
同时,需要将该映射文件的路径写入到 Hibernate 配置文件
hibernate.cfg.xml
中,如下:<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- 配置数据库信息:host、port、database、user、password 需要替换为数据库管理员提供的数据库相关信息。 --><property name="hibernate.connection.driver_class">com.tencentcloud.tdsql.pg.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:tdsql-pg://host:port/database?oracle_compile=true</property><property name="hibernate.connection.username">user</property><property name="hibernate.connection.password">password</property><!-- 配置数据库方言 --><property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL10Dialect</property><!-- 新增映射文件路径 --><mapping resource="com/tencentcloud/tdsql/pojo/Student.hbm.xml"/></session-factory></hibernate-configuration>
封装数据库表的增删查改操作
然后,在
TDSQL_PG_Hibernate/src/main/java/
下创建 Package com.tencentcloud.tdsql.dao
,在TDSQL_PG_Hibernate/src/main/java/com/tencentcloud/tdsql/dao
下新建StudentDao
类,定义与数据库交互相关的方法,以实现数据的增删查改,如下:package com.tencentcloud.tdsql.dao;import com.tencentcloud.tdsql.pojo.Student;import java.util.List;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import org.hibernate.query.Query;public class StudentDao {private Session session = null;{// 读取 hibernate.cfg.xmlConfiguration cfg = new Configuration().configure();SessionFactory sessionFactory = cfg.buildSessionFactory();// 打开一个 sessionsession = sessionFactory.openSession();}// 插入public int insertStudent(Student student) {session.beginTransaction();session.save(student);session.getTransaction().commit();return 1;}// 查询public List<Student> selectAllStudent() {String sql = "from Student order by id";Query query = session.createQuery(sql);List<Student> students = query.list();return students;}// 更新public int updateStudentById(Student student) {session.beginTransaction();Student student1 = session.get(Student.class, student.getId());session.merge(student);session.getTransaction().commit();return 1;}// 删除public int deleteStudentById(int id) {session.beginTransaction();Student student = session.get(Student.class, id);session.delete(student);session.getTransaction().commit();return 1;}}
更多 Hibernate 操作,请查询 Hibernate 官网。
测试
最后,在
TDSQL_PG_Hibernate/src/test/java
下添加测试类TestStudent
,展示了基本的增删查改功能,如下:import com.tencentcloud.tdsql.dao.StudentDao;import com.tencentcloud.tdsql.pojo.Student;import java.util.List;import org.junit.jupiter.api.Test;public class TestStudent {@Testpublic void test() {StudentDao studentDao = new StudentDao();System.out.println("------插入数据------");studentDao.insertStudent(new Student(1, "Alex"));studentDao.insertStudent(new Student(2, "Bob"));studentDao.insertStudent(new Student(3, "John"));System.out.println("插入3条数据");System.out.println("------查询数据------");List<Student> students1 = studentDao.selectAllStudent();for (Student student: students1) {System.out.println(student);}System.out.println("------更改数据------");studentDao.updateStudentById(new Student(1, "Alice"));System.out.println("更改id为1的数据");System.out.println("------查询数据------");List<Student> students2 = studentDao.selectAllStudent();for (Student student: students2) {System.out.println(student);}System.out.println("------删除数据------");studentDao.deleteStudentById(2);System.out.println("删除id为2的数据");System.out.println("------查询数据------");List<Student> students3 = studentDao.selectAllStudent();for (Student student: students3) {System.out.println(student);}}}
运行结果如下:
------插入数据------插入3条数据------查询数据------Student [id=1, name=Alex]Student [id=2, name=Bob]Student [id=3, name=John]------更改数据------更改id为1的数据------查询数据------Student [id=1, name=Alice]Student [id=2, name=Bob]Student [id=3, name=John]------删除数据------删除id为2的数据------查询数据------Student [id=1, name=Alice]Student [id=3, name=John]
附:项目结构
至此,完成了 Hibernate 项目的配置和开发示例,项目的整体结构如下图所示:

