Skip to content
Advertisement

JPA cascade actions on one-to-one relationship

I have the following question regarding one to one relationships (and I guess one to many also):

Let’s suppose I have the following tables:

JavaScript
JavaScript

As you can see the two tables share the same primary key. Now the entities I created are the following:

JavaScript
JavaScript

When I try to persist a new user I have a user object with all the values generated except of the user.id and the userDetail.userId. When I try to persist this the error I get is the following:

JavaScript

Note that to save a User entity I created this interface:

JavaScript

and I use the save method provided.

JavaScript

the object before saving looks like this:

JavaScript

I was wondering if I can simply save a user object and cascade the generated key to the userDetail.

Should I use another approach for saving or there is something wrong with my entities?

Advertisement

Answer

You’ve done things from the wrong direction.

JavaScript

With this, you can just set the userDetail.user reference and JPA will persist both the user, assign it a ID and use that to populate the UserDetail.id value for you – in your model and in the database.

You should maintain the user.userDetail reference, but it is less consequential to the database row data and more for object consistency reasons.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement