views:

234

answers:

1

Hi all,

Considering Hibernate 3,

I have a parent table, and a child table, linked by a foreign key. I declare a many-to-one association into parent hbm file with a cascade all property. I first persit a parent (save or persist) and it saves a parent and a child. Fine so far. But in another session, i create a new parent object (functionnaly different than the one of the first session) and i make a reference to a new child object (but which is functionnaly the SAME than the one of the first session, and it is a Transient object at this point)

I would like to know if Hibernate may natively support and identify that i am managing the same child (and so do not try to persist it when i save the new parent) or do i have to develop a roundtrip to database and check if the child is already present?

Thanks all

A: 

Hibernate identifies objects by its primary key. So if these two children have the same primary key, which needs to be a business generated key, Hibernate would know that it is the same object. BUT, it still doesn't know if it should perform an update or an insert to the database. You could call merge explicitly on the child, Hibernate will search it in the database, and either create or update it.

BUT, It is not as easy as this:

One problem is the business generated key. It is better to let Hibernate generate surrogate keys.

Another problem is the need to use merge, which must be used always if this class is stored. Consider to remove the cascade, because you have to store it explicitly anyway.

Note that merge returns another instance that needs to be used. (this means: assign the return value of merge to the property of the parent.)

The root problem you've got is that the business logic is creating the same object twice. If you want to reuse an instance that has been created by someone else, you need to get it, either by searching it in the database or by passing it as argument. Try to solve the problem like this before you try any workarounds.

Stefan Steinegger