Hibernate Entity Classes and CRUD With the Session: persist, find, a Setter and remove
Four small programs against a three-row users table: persist adds Noah and the id comes back as 4, find reads Emma (twice, with one SELECT), a setter changes Liam's email, and remove deletes Noah. Every change goes out at commit.
What you will learn
- Map a User class to the users table with @Entity, @Table, @Id and @GeneratedValue
- Insert with persist and see the generated id come back
- Read with find, and see the session return the same object without new SQL
- Update with a plain setter and delete with remove, both sent at commit
Before you start
- Hibernate 7 Setup
- Why an ORM: The Same UserDao in JDBC and in Hibernate
With Hibernate your code works with plain Java objects, and the session sits in the middle. It keeps track of your objects and writes the SQL for the database. This article runs four small programs, one per CRUD action.
You call Java, Hibernate sends SQL
The users table and the plan
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) NOT NULL UNIQUE
);
INSERT INTO users (name, email) VALUES
('Emma Clark', '[email protected]'),
('Liam Turner', '[email protected]'),
('Olivia Brooks', '[email protected]');
The Dockerfile runs this file with sqlite3 to build studyeasy.db and copies it into the app's home folder, and hibernate.cfg.xml points at that same file. Docker fills the table and Hibernate reads and writes it. In IntelliJ, db/reset.sql puts the three rows back any time.
The plan: Ex01 adds Noah Bennett (he'll get id 4), Ex02 reads Emma and asks for id 99, Ex03 changes Liam's email, Ex04 removes Noah. Run them in order on a fresh table, because Ex04 removes the user Ex01 added.
A class that maps to a table
package org.studyeasy.hibernate;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity // this class is a table
@Table(name = "users") // the table name
public class User {
@Id // the primary key, filled by the database (AUTOINCREMENT)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name; // column name
private String email; // column email
protected User() { } // Hibernate needs an empty one
public User(String name, String email) {
this.name = name;
this.email = email;
}
public Integer getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
public void setName(String name) { this.name = name; }
public void setEmail(String email) { this.email = email; }
@Override
public String toString() {
return "User " + id + ": " + name + " <" + email + ">";
}
}
@Entity says this class is a table, and @Table(name = "users") names it. These annotations come from JPA: JPA is the standard, and Hibernate implements it. @Id with GenerationType.IDENTITY means the database fills the key, matching the AUTOINCREMENT column. name and email become columns. The empty protected constructor is needed because, when Hibernate reads a row, it first builds an empty User and then fills the fields.
persist: a new row
package org.studyeasy.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Ex01_CreateUser {
public static void main(String[] args) {
SessionFactory factory =
new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction(); // a change needs a transaction
User noah = new User("Noah Bennett", "[email protected]");
System.out.println("Before persist: " + noah);
session.persist(noah); // INSERT, the id comes back
System.out.println("After persist: " + noah);
session.getTransaction().commit(); // the row is saved
session.close();
factory.close();
}
}
Before persist: User null: Noah Bennett <noah.bennett@example.com>
Hibernate: insert into users (email,name) values (?,?)
Hibernate: select last_insert_rowid()
After persist: User 4: Noah Bennett <noah.bennett@example.com>
A change needs a transaction, so it begins first. persist is the INSERT, and we didn't write it. Before persist the id was null; after, it's 4. The database gave Noah his id and Hibernate read it back.
find: a row by its key
package org.studyeasy.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Ex02_ReadUser {
public static void main(String[] args) {
SessionFactory factory =
new Configuration().configure().buildSessionFactory();
Session session = factory.openSession(); // no transaction
User emma = session.find(User.class, 1); // SELECT by primary key
System.out.println("Found: " + emma);
User again = session.find(User.class, 1); // cached: no SQL
System.out.println("Same object: " + (emma == again));
User missing = session.find(User.class, 99); // no row with id 99
System.out.println("Id 99: " + missing);
session.close();
factory.close();
}
}
Hibernate: select u1_0.id,u1_0.email,u1_0.name from users u1_0 where u1_0.id=?
Found: User 1: Emma Clark <[email protected]>
Same object: true
Hibernate: select u1_0.id,u1_0.email,u1_0.name from users u1_0 where u1_0.id=?
Id 99: null
No transaction here, since we only read. find needs only the class and the id to build one SELECT by primary key. The second find for id 1 sends no SQL: the session remembers every object it has loaded and hands back the very same Emma, so == is true. For id 99 there's no row, and find returns null rather than throwing.
Update: just a setter
package org.studyeasy.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Ex03_UpdateUser {
public static void main(String[] args) {
SessionFactory factory =
new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
User liam = session.find(User.class, 2);
liam.setEmail("[email protected]"); // just a setter
System.out.println("Changed: " + liam);
session.getTransaction().commit(); // UPDATE goes out
session.close();
factory.close();
}
}
Hibernate: select u1_0.id,u1_0.email,u1_0.name from users u1_0 where u1_0.id=?
Changed: User 2: Liam Turner <liam.t@example.com>
Hibernate: update users set email=?,name=? where id=?
Liam was loaded through the session, so the session watches him. We change the object with a plain setter. At commit, Hibernate compares Liam with what it loaded, spots the change and sends the UPDATE. Load it, change it, commit it.
remove: the row is gone
package org.studyeasy.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Ex04_DeleteUser {
public static void main(String[] args) {
SessionFactory factory =
new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
User noah = session.find(User.class, 4); // the user Ex01 added
session.remove(noah); // load first, then remove
session.getTransaction().commit(); // DELETE
System.out.println("Deleted: " + noah);
System.out.println("Id 4 now: " + session.find(User.class, 4));
session.close();
factory.close();
}
}
Hibernate: select u1_0.id,u1_0.email,u1_0.name from users u1_0 where u1_0.id=?
Hibernate: delete from users where id=?
Deleted: User 4: Noah Bennett <noah.bennett@example.com>
Hibernate: select u1_0.id,u1_0.email,u1_0.name from users u1_0 where u1_0.id=?
Id 4 now: null
Load first, then remove. The DELETE goes out at commit, and the next find returns null. We're back to three rows.
Common mistakes
- Running Ex01 twice without a reset. The email is UNIQUE, so the second INSERT fails with
UNIQUE constraint failed: users.email. - Using the result of
findwithout a null check.missing.getName()on id 99 throws aNullPointerException. - Detaching an object before changing it. After
session.detach(liam)the session no longer watches him, commit sends no UPDATE, and the row keeps the old email. - Removing something that isn't there. Run Ex04 again and
findreturns null:IllegalArgumentException: Entity may not be null.
Quick recap
| Action | Call | Transaction? |
|---|---|---|
| Create | persist | yes |
| Read | find (null if missing) | no |
| Update | a setter on a loaded object | yes, sent at commit |
| Delete | find then remove | yes, sent at commit |
To work with many rows at once, see HQL: listing, where, update and delete.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
SQLite and a JDBC Connection Pool in a Java Web App
A whole database in one file, studyeasy.db, and a Java web app that talks to it: one HikariCP pool, a @WebListener that opens it and runs schema.sql at startup, and a /db-check servlet that borrows a connection.
Why an ORM: The Same UserDao in JDBC and in Hibernate
One UserDao, written twice. The JDBC version spells out every SQL string and copies every column; the Hibernate version persists, finds and merges objects and lets Hibernate write the SQL. 66 lines against 40, and what that costs.
Hibernate 7 Setup: Three Dependencies, hibernate.cfg.xml and a First Session
Four pieces, one job each: three Maven dependencies, a two-property hibernate.cfg.xml, one SessionFactory per app and one Session per piece of work. A small main method proves it: Rows in users: 3.
Hibernate Inside a Servlet Web App: Replace the JDBC DAO, Keep Every Page
The Users web app's UserDao, rewritten with Hibernate: same five methods, no SQL strings, one SessionFactory built on the existing HikariCP pool, and zero of the eight servlets and JSPs changed.
