使用Hibernate开发ProtonBase应用示例
ProtonBase 支持基于主流 ORM(Object-Relational Mapping)框架开发应用,Hibernate 是 Java 语言下的对象关系映射解决方案。本文介绍基于 Hiberante 如何快速开发。
准备工作
- 在 ProtonBase 上创建 database
CREATE DATABASE example;
- 在新创建的 database 上创建 table
CREATE TABLE customer (
id bigint NOT NULL,
name text NOT NULL,
email text NOT NULL,
create_time timestamp DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
Hibernate 示例
Hibernate 是 Java 语言下的对象关系映射解决方案。
- 引入 hibernate 依赖。用 maven 管理本项目,在 pom.xml 中加入以下内容:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.3.Final</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.12</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
- 定义实体类,每一张表都需要对应一个实体类。这里我们只有一张 customer 表,只需要编写一个 Customer 类即可。在定义实体类时,我们需要指明字段与数据库列的对应关系。
package com.xiaozhi;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="customer")
public class Customer {
@Id
@Column(name="id")
private Long id;
@Column(name="name", nullable = false)
private String name;
@Column(name="email", nullable = false)
private String email;
@Column(name="create_time", columnDefinition = "timestamp DEFAULT CURRENT_TIMESTAMP")
private Timestamp createTime;
}
- 编写配置文件 hibernate.cfg.xml。
<!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>
<!-- JDBC Database connection settings -->
<property name="dialect">org.hibernate.dialect.PostgreSQL82Dialect</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/example?sslmode=disable</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">false</property>
<mapping class="com.xiaozhi.Customer" />
</session-factory>
</hibernate-configuration>
- 通过以下代码,先向 customer 表中插入(insert)两条新纪录,然后查询(select)cluster 表验证插入已生效;再修改(update)其中的一条记录,查询表中记录验证修改已生效;最后删除其中一条记录,查询表中记录验证删除已生效。
package com.xiaozhi;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
public class Main {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().
configure("hibernate.cfg.xml").buildSessionFactory();
// Insert
insert(sessionFactory);
// Select
System.out.println("Result of the first selection:");
select(sessionFactory);
// Update
update(sessionFactory);
// Select
System.out.println("Result of the second selection:");
select(sessionFactory);
// Delete
delete(sessionFactory);
// Select
System.out.println("Result of the third selection:");
select(sessionFactory);
}
// Insert
private static void insert(SessionFactory sessionFactory) {
Transaction transaction = null;
try (Session session = sessionFactory.openSession()) {
transaction = session.beginTransaction();
Customer firstCustomer = new Customer(1L, "Jacob Emily", "jacob.emily@protonbase.io", Timestamp.valueOf(LocalDateTime.now()));
session.save(firstCustomer);
Customer secondCustomer = new Customer(2L, "Michael Emma", "michael.emma@protonbase.io", Timestamp.valueOf(LocalDateTime.now()));
session.save(secondCustomer);
transaction.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
if (transaction != null) {
transaction.rollback();
}
}
}
// Select
private static void select(SessionFactory sessionFactory) {
Session session = sessionFactory.openSession();
List<Customer> customers = session.byMultipleIds(Customer.class).multiLoad(1L, 2L);
for (Customer customer : customers) {
if (customer != null) {
System.out.println(customer);
}
}
session.close();
}
// Update
private static void update(SessionFactory sessionFactory) {
Transaction transaction = null;
try (Session session = sessionFactory.openSession()) {
transaction = session.beginTransaction();
Customer customer = session.get(Customer.class, 2L);
customer.setEmail("michael.emma@gmail.com");
session.update(customer);
transaction.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
if (transaction != null) {
transaction.rollback();
}
}
}
// Delete
private static void delete(SessionFactory sessionFactory) {
Transaction transaction = null;
try (Session session = sessionFactory.openSession()) {
transaction = session.beginTransaction();
Customer customer = session.get(Customer.class, 1L);
session.delete(customer);
transaction.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
if (transaction != null) {
transaction.rollback();
}
}
}
}
运行结果如下:
Result of the first selection:
Customer(id=1, name=Jacob Emily, email=jacob.emily@protonbase.io, createTime=2023-10-29 00:27:15.502447)
Customer(id=2, name=Michael Emma, email=michael.emma@protonbase.io, createTime=2023-10-29 00:27:15.516256)
Result of the second selection:
Customer(id=1, name=Jacob Emily, email=jacob.emily@protonbase.io, createTime=2023-10-29 00:27:15.502447)
Customer(id=2, name=Michael Emma, email=michael.emma@gmail.com, createTime=2023-10-29 00:27:15.516256)
Result of the third selection:
Customer(id=2, name=Michael Emma, email=michael.emma@gmail.com, createTime=2023-10-29 00:27:15.516256)