Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hibernate class A containing a list of B

 
Bart Saelen
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I need some help.
I'm writing an application to import data in a database from files. In this application I have a class A that contains a set of class B.

class A

class B


Now I want to insert these into the database with hibernate. And if A already exists in the database, I want to update it. When A is updated I only want the related B objects from the latest update of the related A object in the database.

I wrote these hibernate mappings:
A.hbm.xml


B.hbm.xml


When I insert an A object that is already in the database:
-it updates the existing object (this is correct)
-it inserts the B objects related to the new A object (this is correct)
-it keeps the previously related B objects in the database (this is the problem)

How can I configure hibernate to only keep the most recent B objects?
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
cascade options.

You have "all" that includes "delete" but it does not include "delete-orphan", so the previous Bs will just have their FK value set to null.

If you try

"all, delete-orphan" I believe you will see what you want.

Mark
 
Bart Saelen
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the reply Mark

I changed the cascade option to "all, delete-orphan", but it doesn't work the way I want it.

new hibernate mapping A.hbm.xml


In my database I have the following, after updating the parent with a child (2,'test 1 2 3 . ') :
id text parent
---------------------------------
1 test 1 2 3 ... 22009
2 test 1 2 3 . 22009

What I wan't is that the previous child isn't linked anymore to the parent.
So the database would have something like this:
id text parent
---------------------------------
1 test 1 2 3 ...
2 test 1 2 3 . 22009

or even better something like this:
id text parent
---------------------------------
2 test 1 2 3 . 22009
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I though you said you wanted to delete the record that was removed from the set? That is what the delete-orphan is used for. Also "all" includes delete. Maybe the feature you want will be with using "save-update" alone, or not, I suggest looking at the cascade options and picking which ones you want.

But basically, it is in cascade options that cause how related objects react to including or removing objects from sets and lists.

Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic