Skip to content
Advertisement

Relationship mapping in Hibernate Java – save owning side entity

I have 2 tables

  • User
  • Url

I’m trying to create a relationship between said 2 tables. A user can have many urls, but a url can belong to only one user.

This sounds to me like a OneToMany relationship.

My User Entity is as follows(some code was removed as to not make it too long):

JavaScript

My Url Entity is as follows(some code was removed as to not make it too long):

JavaScript

I’ve been following a relatively simple guide which I’ve found here.

Now my question is: How do I save the owning side entity?

Say I already have a user created.

JavaScript

I add a new url for that user

JavaScript

And now what?

I’ve tried

JavaScript

But that results in an errror:

JavaScript

Of course, I could be going about this all wrong, perhaps my relationship is not correct to begin with?

I’m very open to ideas.

Advertisement

Answer

You configure the relation between User and Url correctly. It mainly complains when it saves an Url , its User is a new record.

The problem can be fixed if you save the User first :

JavaScript

But since you already configure cascade is ALL for User ‘s Url , all JPA operations applied on User will automatically applied to its Url too , which means you can simply do :

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