tacnode

Hibernate Development Example

Tacnode supports application development using popular ORM (Object-Relational Mapping) frameworks. Hibernate is a Java object-relational mapping solution. This article explains how to develop applications efficiently using Hibernate.

Preparation

  1. Set up a database in Tacnode.
CREATE DATABASE example;
  1. Establish a table in the newly created database.
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 Example

Hibernate serves as an object-relational mapping solution for Java.

  1. Add the Hibernate dependency. Use Maven to manage this project and insert the following content into 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>
  1. Define entity classes. Each table must correspond to an entity class. Since there is only one customer table, create a Customer class. When defining this entity class, ensure the fields correspond to the database columns.
package io.tacnode;
 
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;
}
  1. Update the configuration file 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="io.tacnode.Customer" />
    </session-factory>
</hibernate-configuration>
  1. Add two new records to the customer table in this code. Then, query the customer table to confirm the insertion succeeded. Update one of the records, query the table again to ensure the modification is reflected, and finally, delete one record and verify the deletion by querying the table again.
package io.tacnode;
 
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@tacnode.io", Timestamp.valueOf(LocalDateTime.now()));
            session.save(firstCustomer);
            Customer secondCustomer = new Customer(2L, "Michael Emma", "michael.emma@tacnode.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();
            }
        }
    }
}

The results are listed below:

Result of the first selection:
Customer(id=1, name=Jacob Emily, email=jacob.emily@tacnode.io, createTime=2023-10-29 00:27:15.502447)
Customer(id=2, name=Michael Emma, email=michael.emma@tacnode.io, createTime=2023-10-29 00:27:15.516256)
Result of the second selection:
Customer(id=1, name=Jacob Emily, email=jacob.emily@tacnode.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)

On this page