Tutorials Logic, IN info@tutorialslogic.com

Hibernate CRUD save, get, update, delete: Tutorial, Examples, FAQs & Interview Tips

Hibernate CRUD save, get, update, delete

Hibernate is a practical Hibernate topic that becomes clear when you connect the definition to a small working example.

Use this page to understand what happens, why it happens, how to verify it, and what mistake usually breaks the concept.

After reading, practice Hibernate with a normal case, a boundary case, and a broken case so the idea becomes usable instead of memorized.

Hibernate CRUD save get update delete should be studied as a practical Hibernate lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the hibernate > crud-operations page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

Session CRUD Methods

Method Description Returns
session.persist(obj) Insert new entity (JPA standard) void
session.save(obj) Insert new entity (Hibernate legacy) Serializable (ID)
session.get(Class, id) Load entity by ID (returns null if not found) Entity or null
session.load(Class, id) Load proxy by ID (throws exception if not found) Proxy
session.update(obj) Update detached entity void
session.merge(obj) Merge detached entity state (JPA standard) Managed entity
session.delete(obj) Delete entity (Hibernate legacy) void
session.remove(obj) Delete entity (JPA standard) void
session.saveOrUpdate(obj) Insert or update based on ID void

Create and Read Operations

Create and Read Operations
public class UserDAO {
    private SessionFactory sessionFactory;

    public UserDAO(SessionFactory sf) { this.sessionFactory = sf; }

    // CREATE
    public Long createUser(User user) {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.persist(user);  // INSERT INTO users ...
            tx.commit();
            return user.getId();
        } catch (Exception e) {
            if (tx != null) tx.rollback();
            throw e;
        } finally {
            session.close();
        }
    }

    // READ by ID - get() returns null if not found
    public User getUserById(Long id) {
        try (Session session = sessionFactory.openSession()) {
            return session.get(User.class, id);
        }
    }

    // READ by ID - load() returns proxy, throws ObjectNotFoundException if not found
    public User getUserProxy(Long id) {
        try (Session session = sessionFactory.openSession()) {
            return session.load(User.class, id); // Lazy proxy
        }
    }

    // READ all
    public List<User> getAllUsers() {
        try (Session session = sessionFactory.openSession()) {
            return session.createQuery("FROM User", User.class).list();
        }
    }
}

Update and Delete Operations

Update and Delete Operations
// UPDATE - modify managed entity (auto-dirty-checking)
public void updateUserEmail(Long id, String newEmail) {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    try {
        User user = session.get(User.class, id);
        if (user != null) {
            user.setEmail(newEmail); // Hibernate detects change automatically
            // No explicit update() needed - dirty checking handles it
        }
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        throw e;
    } finally {
        session.close();
    }
}

// UPDATE - merge detached entity
public User mergeUser(User detachedUser) {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    try {
        User managed = session.merge(detachedUser); // Returns managed copy
        tx.commit();
        return managed;
    } catch (Exception e) {
        tx.rollback();
        throw e;
    } finally {
        session.close();
    }
}

// DELETE
public void deleteUser(Long id) {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    try {
        User user = session.get(User.class, id);
        if (user != null) {
            session.remove(user); // DELETE FROM users WHERE id = ?
        }
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        throw e;
    } finally {
        session.close();
    }
}

// SAVE OR UPDATE
public void saveOrUpdateUser(User user) {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    try {
        session.saveOrUpdate(user); // INSERT if id is null, UPDATE otherwise
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        throw e;
    } finally {
        session.close();
    }
}

Entity States

Hibernate entities can be in one of four states:

  • Transient: Object created with new, not associated with any Session, not in database.
  • Persistent (Managed): Associated with an open Session. Changes are automatically tracked (dirty checking) and synchronized to DB on flush/commit.
  • Detached: Was persistent but Session was closed. Changes are NOT tracked. Use merge() to re-attach.
  • Removed: Marked for deletion. Will be deleted from DB on flush/commit.

Entity State Transitions

Entity State Transitions
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

// 1. TRANSIENT: not associated with session
User user = new User("alice", "alice@example.com");
// user is transient here

// 2. PERSISTENT: associated with session after persist()
session.persist(user);
// user is now persistent - changes tracked automatically

user.setEmail("newalice@example.com"); // Hibernate will UPDATE this

// 3. REMOVED: marked for deletion
session.remove(user);
// user is now removed - will be deleted on commit

tx.commit();
session.close();

// 4. DETACHED: session closed, user is detached
// user.setEmail("another@example.com"); // NOT tracked!

// Re-attach with merge
Session session2 = sessionFactory.openSession();
Transaction tx2 = session2.beginTransaction();
User managed = session2.merge(user); // user becomes managed again
tx2.commit();
session2.close();

Deep Study Notes for Hibernate

Hibernate should be learned as a practical Hibernate skill, not only as a definition. Start by asking what problem the topic solves, what input or state it receives, what rule it applies, and what visible result proves it worked.

A strong explanation of Hibernate includes the normal case, a boundary case, and a failure case. When you practice, write down the before-state, the operation, the after-state, and the reason the result changed.

This lesson was expanded because the audit reported: under 650 content words; limited checklist/practice/mistake/FAQ notes . The added notes below focus on clearer explanation, more examples, and concrete practice so the topic is easier to understand from the page itself.

  • Define the exact problem solved by Hibernate before looking at syntax.
  • Trace one small example by hand and describe every step in plain language.
  • Identify what changes when the input is empty, repeated, invalid, delayed, or larger than expected.
  • Connect the topic to a realistic project scenario instead of treating it as isolated theory.
  • Verify your answer with output, logs, query results, browser behavior, compiler feedback, or a state table.

Worked Explanation: Using Hibernate Correctly

Imagine you are adding Hibernate to a small learning project. The first step is to choose the smallest scenario that still shows the main idea. Avoid starting with a large production design; it hides the concept behind too many details.

Next, isolate the moving parts. Name the input, the rule, the output, and the possible error. This habit makes the topic easier to debug because you can see whether the problem is caused by bad data, wrong configuration, incorrect syntax, timing, permissions, or misunderstanding of the rule.

Finally, compare two versions: one correct version and one intentionally broken version. The broken version is valuable because it teaches you how the topic fails in real work, which is usually what interviews and debugging tasks test.

  • Normal case: show the expected behavior with simple, valid input.
  • Boundary case: test the smallest, largest, empty, repeated, or unusual value that still belongs to the topic.
  • Failure case: introduce one realistic mistake and explain the symptom it creates.
  • Repair step: change one thing at a time so you know exactly what fixed the problem.

Hibernate Hibernate entity example

Hibernate Hibernate entity example
@Entity
@Table(name = "lesson_hibernate")
public class HibernateNote {
    @Id
    private Long id;
    private String status;

    public void markReviewed() {
        this.status = "REVIEWED";
    }
}

Hibernate transaction boundary example

Hibernate transaction boundary example
try (Session session = sessionFactory.openSession()) {
    Transaction tx = session.beginTransaction();
    HibernateNote note = session.find(HibernateNote.class, 1L);
    note.markReviewed();
    tx.commit();
}
// The important idea is to know when Hibernate tracks the object and when SQL is flushed.
Key Takeaways
  • State the purpose of Hibernate in one sentence before using it.
  • Create a tiny Hibernate example that demonstrates the topic without unrelated code.
  • Test one normal input, one edge input, and one incorrect input for Hibernate.
  • Explain the result using before-state, operation, and after-state.
  • Add a verification step such as output, logs, query results, browser behavior, or compiler feedback.
Common Mistakes to Avoid
WRONG Memorizing Hibernate as a definition only.
RIGHT Pair the definition with a small working example and a failure example.
The fastest way to remember the topic is to explain why the output changes.
WRONG Copying syntax without checking the state before and after.
RIGHT Write the input state, apply the rule, then inspect the output state.
State tracing turns confusing behavior into a visible sequence.
WRONG Ignoring the error path for Hibernate.
RIGHT Create one intentionally broken version and document the symptom and fix.
A page is much easier to learn from when it explains both success and failure.
WRONG Memorizing Hibernate CRUD save get update delete without the situation where it is useful.
RIGHT Connect Hibernate CRUD save get update delete to a concrete Hibernate task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Build the smallest working demo for Hibernate and write what each line does.
  • Change one input or setting and predict the result before running it.
  • Break the example in a realistic way, then fix it and describe the repair.
  • Create a two-column note comparing when to use Hibernate and when another approach is better.
  • Explain Hibernate aloud as if teaching a beginner who knows basic Hibernate only.

Frequently Asked Questions

Understand the problem it solves, the input or state it works on, and the visible result that proves the concept is working.

Use one tiny correct example, one boundary example, and one broken example. Compare the output or state after each change.

They often memorize the term without tracing the behavior. Tracing makes the rule easier to remember and debug.

Remember the problem it solves in Hibernate, then attach the syntax or steps to that problem.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.