简体   繁体   中英

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?

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() {
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM