'Creating a foreign key constraint in JPA and Hibernate
I'm new to JPA. I'm trying to create a relationship between 2 classes, where one is User
class, which has a user_id
field as the primary key. The other class is Party
. I want it to have a user_id
field which will reference to the User
class with a foreign key constraint.
I tried looking out on tutorials but I didn't fully understand how do I reference to a field in a different class. I tried using @OneToOne(targetEntity=User.class, mappedBy="user_id")
and placing it above the user_id
field in the Party
class, but it produced an error saying that it couldn't find the user_id
field.
What could be the problem?
Solution 1:[1]
The mappedBy
is referring to the field in the target class. Try having a User
field in the Party
class, and the other way around. Then annotate the user in the party class with @OneToOne(mappedBy="party")
.
public class User {
Party party;
}
public class Party {
User user;
@OneToOne(mappedBy="party")
public User getUser() {
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | flyingjamus |