Java.Hibernate.Beginner.How do you delete an object in Hibernate?

You delete an object in Hibernate by:
1️⃣ Loading or attaching the entity you want to delete in an active session.
2️⃣ Calling session.delete(entity) to mark it for deletion.
3️⃣ Committing the transaction to execute the SQL DELETE.

🔹 Example of deleting a persistent entity:

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

User user = session.get(User.class, 1L); // load entity to delete

if (user != null) {
    session.delete(user);               // marks entity for deletion
}

tx.commit();                            // executes DELETE
session.close();

✅ Here:

  • session.get() loads the entity → becomes persistent.
  • session.delete() schedules a SQL DELETE for the entity.
  • tx.commit() flushes the change → deletes the record in the database.

🔹 Deleting a detached entity:

  • If you have a detached object (e.g., from a previous session), you can still delete it by reattaching:
User detachedUser = new User();
detachedUser.setId(1L);                // ID of the row to delete

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

session.delete(detachedUser);          // Hibernate deletes based on ID

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

✅ Hibernate will issue a DELETE for the specified ID, even if the detached entity wasn’t fully loaded.

🔹 Important notes:

  • Always call delete() inside an active transaction.
  • If the entity is transient (never saved), calling delete() does nothing (no SQL issued).
  • Deleting entities with relationships may require proper cascade settings (e.g., CascadeType.REMOVE) to delete related records.

Key takeaway:
Use session.delete(entity) inside a transaction to delete persistent or detached objects → then commit to apply the change.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.