[英]Creating a foreign key constraint in JPA and Hibernate
I'm new to JPA.我是 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.我正在尝试在 2 个类之间创建关系,其中一个是
User
类,它有一个user_id
字段作为主键。 The other class is Party
.另一个类是
Party
。 I want it to have a user_id
field which will reference to the User
class with a foreign key constraint.我希望它有一个
user_id
字段,它将引用具有外键约束的User
类。
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.我尝试使用
@OneToOne(targetEntity=User.class, mappedBy="user_id")
并将其放在Party
类中的user_id
字段上方,但它产生了一个错误,提示它找不到user_id
字段。
What could be the problem?可能是什么问题呢?
The mappedBy
is referring to the field in the target class. mappedBy
指的是目标类中的字段。 Try having a User
field in the Party
class, and the other way around.尝试在
Party
类中有一个User
字段,反之亦然。 Then annotate the user in the party class with @OneToOne(mappedBy="party")
.然后使用
@OneToOne(mappedBy="party")
在派对类中注释用户。
public class User {
Party party;
}
public class Party {
User user;
@OneToOne(mappedBy="party")
public User getUser() {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.