0

I've created an Object A {id: long (AutIncrement), name:String} , which I'll saveOrupdate with hibernate.

I want to know, before A being save, which will be the generated Id. I need it , because I need to set properties in A that depends on properties of an object B, but I've also properties in B depending on object A.

It's kind of a circular dependency. When filling B I need the id of A, when filling A, I need one generated property of B.

Is there a way to know prior to save A, which will its ID.

Thanks in advance rgd

user1680680
  • 213
  • 2
  • 9
  • The answer to your question is "no": depending on the database, the ID might not be generated until the insert completes. Your real problem, however, are the circular dependencies. You can probably get rid of them by changing your table structure. But since you don't show your table structure here, we can't help you with that (hint: edit your question to something that's answerable). – kdgregory Jul 09 '14 at 17:14

2 Answers2

0

You will not have access to the id, until after flush time, You can add a cascade Insert/update to the relationship, but this can lead you to hell, especially when you have circular dependency. I would do what @kdgregory said, change your table structure.

botossi
  • 11
  • 2
0

As stated by kdgregory, the general answer is that it is not possible. This kind of circular dependancy is generally the sign of a problem is database structure design.

That being said, if you really want to do it you can manually declare a sequence in your database, say to hibernate that the primary key generation strategy is assigned (it is enough not to include any generator). Then in you application, when creating a new A, you first get its id from the sequence, put it it you object, do what you need with objects depending on it and finally persist it.

But beware, as the time of persisting B, the id of A will be known, but obviously no A will be present in database.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252