Hibernate – Add (Insert) a New Record
Adding a new record using Hibernate requires three steps: open a session, begin a transaction, call session.persist() (or session.save()), and commit. This tutorial walks through a complete working example using a Product entity and a MySQL database.
Prerequisites
- Java 8 or later
- Hibernate 5.x
- MySQL database
- Maven project
Database Table
CREATE TABLE product (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(45) DEFAULT NULL,
price DECIMAL(10,0) DEFAULT NULL,
quantity INT DEFAULT NULL,
description VARCHAR(450) DEFAULT NULL,
active TINYINT(1) DEFAULT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.15.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/java9rdb</property>
<property name="connection.username">root</property>
<property name="connection.password">yourpassword</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.java9r.model.Product"/>
</session-factory>
</hibernate-configuration>
Product Entity
package com.java9r.model;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "name", length = 45)
private String name;
@Column(name = "price")
private Long price;
@Column(name = "quantity")
private Integer quantity;
@Column(name = "description", length = 450)
private String description;
@Column(name = "active")
private Boolean active;
@Column(name = "created_at")
private LocalDateTime createdAt;
public Product() {}
public Product(String name, Long price, Integer quantity,
String description, Boolean active) {
this.name = name;
this.price = price;
this.quantity = quantity;
this.description = description;
this.active = active;
this.createdAt = LocalDateTime.now();
}
// Getters
public Integer getId() { return id; }
public String getName() { return name; }
public Long getPrice() { return price; }
public Integer getQuantity() { return quantity; }
public String getDescription() { return description; }
public Boolean getActive() { return active; }
public LocalDateTime getCreatedAt() { return createdAt; }
// Setters
public void setName(String name) { this.name = name; }
public void setPrice(Long price) { this.price = price; }
public void setQuantity(Integer quantity) { this.quantity = quantity; }
public void setDescription(String description) { this.description = description; }
public void setActive(Boolean active) { this.active = active; }
@Override
public String toString() {
return String.format("Product{id=%d, name='%s', price=%d, qty=%d, active=%s}",
id, name, price, quantity, active);
}
}
HibernateUtil – SessionFactory Helper
package com.java9r.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
sessionFactory.close();
}
}
ProductDAO – Add New Record
package com.java9r.dao;
import com.java9r.model.Product;
import com.java9r.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class ProductDAO {
public void addNewRecord(Product product) {
Transaction tx = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
tx = session.beginTransaction();
session.persist(product); // or session.save(product)
tx.commit();
System.out.println("Successfully inserted: " + product);
} catch (Exception e) {
if (tx != null) tx.rollback();
throw e;
}
}
}
Main Class
package com.java9r;
import com.java9r.dao.ProductDAO;
import com.java9r.model.Product;
import com.java9r.util.HibernateUtil;
public class AddProductMain {
public static void main(String[] args) {
ProductDAO dao = new ProductDAO();
Product p = new Product(
"Wireless Mouse", // name
1500L, // price (INR)
50, // quantity
"Ergonomic wireless mouse with USB receiver",
true // active
);
dao.addNewRecord(p);
HibernateUtil.shutdown();
}
}
Expected Output
Hibernate: insert into product (active, created_at, description, name, price, quantity)
values (?, ?, ?, ?, ?, ?)
Successfully inserted: Product{id=1, name='Wireless Mouse', price=1500, qty=50, active=true}
persist() vs save() – Which to Use?
| Method | JPA Standard? | Returns | Outside Transaction? |
|---|---|---|---|
session.persist() |
Yes (JPA) | void | Throws exception |
session.save() |
No (Hibernate-only) | Serializable (generated id) | Works but not recommended |
Prefer persist() for new code — it is the JPA-standard method and works correctly across providers.
Summary
Inserting a record with Hibernate requires: open a session, start a transaction, call session.persist(entity), and commit. If an exception occurs, always roll back the transaction. The @GeneratedValue(strategy = GenerationType.IDENTITY) annotation lets the database auto-generate the primary key — Hibernate reads it back and populates the entity's id field after the insert.
Comments