Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Hibernate
  • SQLite and a JDBC Connection Pool in a Java Web App
  • Why an ORM: The Same UserDao in JDBC and in Hibernate
  • Hibernate 7 Setup: Three Dependencies, hibernate.cfg.xml and a First Session
  • Hibernate Entity Classes and CRUD With the Session: persist, find, a Setter and remove
  • Hibernate Inside a Servlet Web App: Replace the JDBC DAO, Keep Every Page
  • Spring MVC and SQLite Without Spring Boot: the Mini Blog in the Browser
  • Hibernate Entity Classes and CRUD With the Session: persist, find, a Setter and remove
  • Entities and H2 in Spring Boot: a Post Class Becomes a Table
  • JPA Entity Mapping: Ids, Enums and Dates, From a Java Class to a Table
  • HQL in Hibernate 7: List, Where With a Named Parameter, Bulk Update and Bulk Delete
  • The N+1 Problem in JPA: Fetch Types, Join Fetch and Entity Graphs
  1. Blog
  2. /
  3. Hibernate
  4. /
  5. Fundamentals

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

What you will learn

  • Explain what a DAO is and why its insides can be swapped
  • Rewrite findAll and update from JDBC to Hibernate
  • Wire one SessionFactory onto the existing HikariCP pool
  • Read the before-and-after numbers: what shrinks, what grows, what Hibernate sends

Before you start

  • Users CRUD With Servlets and JSP, Part 2
  • HQL in Hibernate 7

The Users web app talks to the database through one class, UserDao. In this article we rewrite that one class with Hibernate and compare it line by line with the JDBC version. Nothing else in the app changes.

What is a DAO?

DAO stands for Data Access Object: the one class that talks to the database for one kind of data. Everyone else just calls its methods.

Servlets and JSPs on the left call UserDao in the middle, with five methods insert, findAll, findById, update and delete. Only UserDao talks to studyeasy.db on the right. The inside of UserDao switches from JDBC to Hibernate while the callers stay the same. Servlets + JSPs UserController, Save/DeleteUserServlet UserDao insert, findAll, findById, update, delete inside: JDBC → Hibernate studyeasy.dbusers
Same names, same parameters, same return types. Only the inside of the DAO changes.

Why bother? All the data code (connections, SQL, turning rows into objects) lives in one place. Callers pass a User and get a User back; they never see a ResultSet. And the insides can be swapped, which is the whole point of this lesson.

Five methods, same names, new insides

MethodJDBC versionHibernate version
insertINSERT INTO users ...session.persist
findAllSELECT ... ORDER BY idHQL from User order by id
findByIdSELECT ... WHERE id = ?session.find
updateUPDATE users SET ...session.merge
deleteDELETE FROM users ...find, then session.remove

Load every user: JDBC vs Hibernate

The JDBC findAll from the starter project writes the SQL string, borrows a connection, prepares and runs the query, loops with rs.next(), builds a User from getInt and two getString calls per row, and catches the SQLException. Fifteen lines to read one table (see the JDBC DAO). The Hibernate version is seven lines with one line of logic:

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();
    }
}

Save a change: JDBC vs Hibernate

JDBC update writes UPDATE users SET name = ?, email = ? WHERE id = ? and fills the question marks by hand with setString(1, ...), setString(2, ...) and setInt(3, ...). Get the order wrong and you update the wrong column. Hibernate:

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
    }
}

Why merge and not persist? The User here comes from the edit form; this session never loaded it. merge copies its values onto the row with the same id, and at commit Hibernate sends the UPDATE. The SQL didn't vanish. It moved into User.java once, as @Entity, @Table(name = "users") and @Id with IDENTITY, and Hibernate writes INSERT, UPDATE and DELETE from that mapping.

One config, one factory, a Session per call

Three small pieces plug Hibernate into the web app. First, a new hibernate.cfg.xml, with no URL and no password in it:

<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration xmlns="http://www.hibernate.org/xsd/orm/cfg">
    <session-factory>
        <!-- no URL or password here: Database.java hands Hibernate
             the HikariCP pool the app already has -->

        <!-- print every SQL statement Hibernate sends -->
        <property name="hibernate.show_sql">true</property>

        <!-- the entity classes Hibernate maps to tables -->
        <mapping class="org.studyeasy.web.model.User"/>
    </session-factory>
</hibernate-configuration>

Second, Database.java gets a SessionFactory next to the existing pool, and hands Hibernate that pool:

package org.studyeasy.web.db;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

// One pool for the whole app: connections are opened once,
// then lent out and given back, instead of a new one per request.
// One SessionFactory for the whole app too, built on that pool.
public class Database {

    private static final HikariDataSource POOL = createPool();
    private static final SessionFactory FACTORY = createFactory();

    private static HikariDataSource createPool() {
        HikariConfig config = new HikariConfig();
        // the whole database is one file: studyeasy.db in your home folder
        config.setJdbcUrl("jdbc:sqlite:" + System.getProperty("user.home") + "/studyeasy.db");
        // name the driver: a web app's own jars are not on the JVM's path
        config.setDriverClassName("org.sqlite.JDBC");
        config.setMaximumPoolSize(5);
        return new HikariDataSource(config);
    }

    private static SessionFactory createFactory() {
        Configuration config = new Configuration().configure();
        // Hibernate borrows its connections from the same pool
        config.getProperties().put("hibernate.connection.datasource", POOL);
        return config.buildSessionFactory();
    }

    public static DataSource getDataSource() {
        return POOL;
    }

    public static SessionFactory getSessionFactory() {
        return FACTORY;
    }

    // runs schema.sql (src/main/resources): the tables the app needs
    public static void createTables() {
        try (InputStream in = Database.class.getResourceAsStream("/schema.sql");
             Connection con = POOL.getConnection();
             Statement st = con.createStatement()) {
            String sql = new String(in.readAllBytes(), StandardCharsets.UTF_8);
            st.executeUpdate(sql);
        } catch (IOException | SQLException e) {
            throw new IllegalStateException("Could not create the tables", e);
        }
    }

    public static void close() {
        FACTORY.close();
        POOL.close();
    }
}

The line hibernate.connection.datasource is the key: Hibernate borrows its connections from the very same HikariCP pool. One pool, for JDBC and Hibernate both. Third, the DAO itself:

package org.studyeasy.web.dao;

import java.util.List;
import org.hibernate.Session;
import org.studyeasy.web.db.Database;
import org.studyeasy.web.model.User;

// The same five methods as before: the servlets and JSPs never notice.
// Hibernate writes the SQL now, from the @Entity mapping on User.
public class UserDao {

    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
        }
    }
}

The small openSession() helper asks the factory for a new session, and every method opens one in try-with-resources, so it's always closed. Building a SessionFactory is expensive, like starting the engine, so there's one for the whole app. A Session is cheap: one per method call, then thrown away.

The whole project, before and after

Counted in the project files, starter (JDBC) against finished (Hibernate):

JDBCHibernate
Lines in UserDao8462
SQL strings written by hand50
setString/getString column calls130
try/catch SQLException blocks50
Database.java + User.java lines75108
Extra pom dependencieshibernate-core, community dialects
Statements for one add, edit or delete1 each2 each
Servlets and JSPs changed0 of 8

The extra statements are worth knowing about. After an insert Hibernate reads back the new id, and merge and remove first run a SELECT to load the row, then the UPDATE or DELETE.

Common mistakes

  • Writing from users in findAll. HQL only knows classes, so /users answers HTTP 500 with UnknownEntityException: Could not resolve root entity 'users'.
  • Calling persist on the User from the edit form. It isn't new; use merge to update the existing row.
  • Forgetting the <mapping class> line in the config. Hibernate then doesn't know User is an entity.

Quick recap

The DAO shrinks to find, persist, merge and remove. The mapping and the factory move into User and Database, Hibernate sends a few extra SELECTs, and the servlets and JSPs never notice the switch. Same pages, much less DAO code.

Keep going in Hibernate · 5 of 11

Previous
Hibernate Entity Classes and CRUD With the Session: persist, find, a Setter and remove
Next post
Spring MVC and SQLite Without Spring Boot: the Mini Blog in the Browser
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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 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.

On this page

  • What is a DAO?
  • Five methods, same names, new insides
  • Load every user: JDBC vs Hibernate
  • Save a change: JDBC vs Hibernate
  • One config, one factory, a Session per call
  • The whole project, before and after
  • Common mistakes
  • Quick recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.