C
C
Chik-2021-01-19 23:08:50
Hibernate
Chik-, 2021-01-19 23:08:50

Is there a way to get the id of an entity immediately after creation?

I have a parent entity Account which has a Policy
0d0ln.png
Policy-entity collection:
VWaAd.png
In my code, I take an account by id,
then I create a Policy object through new and set it to a reference ("val policy"),
then I add this object to Account.
then I save it through the CrudRepository, it turns out that the Policy object now has an id. The screenshot of the debugger shows that there really is an id in the account collection, but the val policy id link is not
in the collection, a completely new policy instance is created (in the debugger it can be seen that the hash is different)
6Hjce.png

is there any way to have the id immediately directly by the link in val policy?
or somehow get the id of the new object (but not through account.policies.last() and so on)?

for example, if this is a completely new account (and not from the database, as in the example above), then everything is created and an id is also substituted in the val policy link, which can already be used
4V9qG.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2021-01-19
@Maksclub

Generate a UUID for example in the constructor when creating a new entity and that's it
Why call an ORM for such a simple duty? Why OBJECT RELATION MAPPIN (just think of the term) to generate an id?
Moreover, I see that it is already used in number

then I save it through the CrudRepository, it turns out that the Policy object now has an id

Id in your method appears during persist, it is then that Id is generated in UoW (by making an extra request to the database), I suggest not to do it the way most people are used to, but do it the way they used to do it, thinking about good design - generate in the constructor

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question