views:

14

answers:

1

Hi, i have two Entities, "Parent" and "Child", that are linked through a bidirectional one-to-many relationship with the cascade attribute set to "all". When adding a Child object to the Parent children collection using the code below, i can't get the ID of the persisted child until i commit the transaction:

Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
p.addChild(c);
// "c" hasn't an ID (is always zero) 

However, when i persist a child entity by explicitly calling the session.save() method, the ID is created and set immediately, even if the transaction hasn't been committed:

Child c = new Child();
session.save(c);
// "c" has an ID

Is there a way to get the ID of the child entity immediately without calling the session.save() method?

Thanks

+1  A: 

This actually depends on the ID scheme that you use.

If you use auto increment fields (eg MySQL, SQL Server), the ID won't be created until the entity is saved.

If you use sequences (eg Oracle), the ID will be created when the entity is persisted.

I assume then that you have an auto increment field in which case the answer is: no, you can't get an ID without persisting it. That being said, you shouldn't actually need that ID most of the time. Relationships with other entities are handled implicitly. I assume then that you want the ID for some kind of URL parameter or form field? Whatever the case, yes you'll need to save it.

cletus