Jerodev
Jerodev

Reputation: 33186

Hibernate delete object without deleting related objects

I have a database with 3 tables: Slideshows, MediaItemsInSlideshows and Mediaitems. I am using this database with a jsp site using hibernate. I would like to be able to delete a slideshow without deleting the mediaitems. The rows in the MediaItemsInSlideshows should be deleted though.

Currently I use the following code to remove the slideshow. When I use this all mediaitems that were used in the slideshow are gone.

Session session = HibernateUtil.getSessionFactory().openSession();
Slideshow s = this.getSlideshowById(id, session);
session.beginTransaction();
session.delete(s);
session.getTransaction().commit();

This is a visual representation of the database: enter image description here

Upvotes: 0

Views: 689

Answers (1)

Emil Gotsev
Emil Gotsev

Reputation: 223

Deleting A will set the reference to it in B to null which is forbidden by the schema. An alternative to changing the order of deletions would be to add a reverse one-to-many collection in B, with cascaded deletes. Only the deletion of A would than be needed. (source: Deleting of related objects in hibernate)

Upvotes: 1

Related Questions