Menu

CRUD Operations

CRUD Operations

Create, Read, Update, Delete

Basic data operations use four session methods. Older tutorials show save(), update(), saveOrUpdate(), delete(), and load(). These were removed in Hibernate 7, so use the standard methods below.

Old method

Hibernate 7 method

save()persist()
update(), saveOrUpdate()merge() for detached objects
delete()remove()
get() (deprecated)find()
load()getReference()
sessionFactory.inTransaction(session -> {
    session.persist(new Student("Asha"));
});

sessionFactory.inTransaction(session -> {
    Student s = session.find(Student.class, 1L);
    s.setName("Asha K");
});

sessionFactory.inTransaction(session -> {
    Student s = session.find(Student.class, 1L);
    if (s != null) {
        session.remove(s);
    }
});

Code Explanation:

  • persist() makes a new object persistent, and the insert runs at flush or commit.
  • find() loads by primary key and returns null if the row does not exist.
  • The update needs no method call. The loaded student is managed, so dirty checking detects the change at commit.
  • remove() works on a managed entity, so the object is loaded first.
  • getReference() returns a lazy proxy without querying, which is useful when you only need a reference, such as when setting a foreign key.

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details