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.
What you will learn
- Explain what an ORM does: objects in your code, rows in a table, SQL written for you
- Compare the same five DAO methods written with JDBC and with Hibernate
- Map a class to a table with @Entity, @Table, @Id and @GeneratedValue
- Weigh JDBC against Hibernate: lines of code, portability and jar size
Before you start
- Users CRUD With Servlets and JSP, Part 2
- Java annotations
So far every SQL statement in the Users app was written by hand. Hibernate takes a different approach. You call session.persist(user), and the user lands in the database. You never typed the INSERT.
In this article we take one class, the UserDao from the JDBC web app, and write it twice. JDBC is a good tool, and so is Hibernate. The question is only who writes the SQL.
Hibernate writes the SQL for you
Hibernate doesn't replace JDBC. It sits on top of it, and both end in the same JDBC driver.
JDBC: every line by hand
package org.studyeasy.hibernate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
// The UserDao from the JDBC web app: we write every SQL statement.
public class JdbcUserDao {
public void insert(User user) {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
try (Connection con = Database.getDataSource().getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
// the values travel apart from the SQL: a ' is just a letter
ps.setString(1, user.getName());
ps.setString(2, user.getEmail());
ps.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException("Could not add " + user.getName(), e);
}
}
public List<User> findAll() {
String sql = "SELECT id, name, email FROM users ORDER BY id";
List<User> users = new ArrayList<>();
try (Connection con = Database.getDataSource().getConnection();
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) { // one pass per row
users.add(new User(rs.getInt("id"),
rs.getString("name"), rs.getString("email")));
}
} catch (SQLException e) {
throw new RuntimeException("Could not list the users", e);
}
return users;
}
public User findById(int id) {
String sql = "SELECT id, name, email FROM users WHERE id = ?";
try (Connection con = Database.getDataSource().getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, id); // fills the first ?
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return new User(rs.getInt("id"),
rs.getString("name"), rs.getString("email"));
}
return null; // no user with this id
}
} catch (SQLException e) {
throw new RuntimeException("Could not find user " + id, e);
}
}
public void update(User user) {
String sql = "UPDATE users SET name = ?, email = ? WHERE id = ?";
try (Connection con = Database.getDataSource().getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, user.getName());
ps.setString(2, user.getEmail());
ps.setInt(3, user.getId());
ps.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException("Could not update " + user.getId(), e);
}
}
public void delete(int id) {
String sql = "DELETE FROM users WHERE id = ?";
try (Connection con = Database.getDataSource().getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, id);
ps.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException("Could not delete " + id, e);
}
}
}
Read findById: write the SQL as a string, fill each ? with setInt, and when a row comes back, copy each column into a new User (or return null). Nothing is hidden, which is the nice thing about JDBC. You also write all of it by hand, in all five methods.
Hibernate: the same class, no SQL
package org.studyeasy.hibernate;
import java.util.List;
import org.hibernate.Session;
// The same five methods with Hibernate: it writes the SQL for us.
public class HibernateUserDao {
private Session openSession() {
return Database.getSessionFactory().openSession();
}
public void insert(User user) {
try (Session session = openSession()) {
session.beginTransaction();
session.persist(user); // INSERT: SQLite picks the id
session.getTransaction().commit();
}
}
public List<User> findAll() {
try (Session session = openSession()) {
// HQL names the class User, not the table users
return session.createQuery("from User order by id", User.class)
.getResultList();
}
}
public User findById(int id) {
try (Session session = openSession()) {
return session.find(User.class, id); // null: no such row
}
}
public void update(User user) {
try (Session session = openSession()) {
session.beginTransaction();
// the form's User is not from this session: merge copies
// its values onto the row with the same id
session.merge(user);
session.getTransaction().commit(); // UPDATE
}
}
public void delete(int id) {
try (Session session = openSession()) {
session.beginTransaction();
User user = session.find(User.class, id);
if (user != null) {
session.remove(user); // load first, then remove
}
session.getTransaction().commit(); // DELETE
}
}
}
- Each method opens a session inside a
try, and the session talks to the database. findAllruns the queryfrom User order by idand gets the users back as objects.updatebegins a transaction, callsmergeand commits. There's noUPDATEstatement anywhere; Hibernate writes it at commit.
The same HQL, any database
from User order by id is HQL, the Hibernate Query Language. It names the class User, not the table users. Hibernate reads the entity and writes the SQL for whichever database you use: SQLite, Postgres, Oracle, any database it supports. With JDBC you write each SQL string yourself. A simple select usually carries over as it is, but SQL differs between databases, so moving to Postgres can mean small changes in those strings.
Tell Hibernate: this class is 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;
// One row of the users table, as a Java object.
@Entity // Hibernate maps this class to a table
@Table(name = "users") // the class is User, the table is users
public class User {
@Id // the primary key
@GeneratedValue(strategy = GenerationType.IDENTITY) // AUTOINCREMENT
private int id; // no final: Hibernate fills the fields
private String name;
private String email;
protected User() { // Hibernate builds a User from a row with this
}
public User(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
}
@Entity: Hibernate maps this class to a table.@Table(name = "users"): the class isUser, the table isusers.@Idmarks the primary key;@GeneratedValue(strategy = IDENTITY)means the database fills it in, an auto-increment.- The fields map to columns.
- The empty constructor matters. Hibernate builds a
Userfrom a row with it; without it you get an error.
JDBC or Hibernate?
| JDBC | Hibernate | |
|---|---|---|
| You write | every SQL statement | an entity class |
| Change the database | SQL strings may need adjusting | the same HQL stays |
| Good fit | a tiny application | most applications |
| Lines for these five methods | 66 | 40 |
| Cost | small and fast | about 36 MB of jar files |
Common mistakes
- Writing the table name in HQL,
from users. HQL uses the entity class name,User. - Dropping the no-argument constructor from an entity. Hibernate can't create objects from rows without it.
- Thinking Hibernate removes JDBC from the project. It still uses the JDBC driver underneath.
Quick recap
Map a class with @Entity, ask with HQL on that class, and get rows back as objects. Next: set up Hibernate 7.
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.
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 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.
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.
