在JPA和Hibernate中创建外键约束
我是JPA的新手.我正在尝试在2个类之间创建一种关系,其中一个是User
类,该类具有一个user_id
字段作为主键.另一个类是Party
.我希望它有一个user_id
字段,该字段将引用带有外键约束的User
类.
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.
我尝试查看教程,但是我不完全了解如何引用不同类中的字段.我尝试使用@OneToOne(targetEntity=User.class, mappedBy="user_id")
并将其放在Party
类中的user_id
字段上方,但是它产生一个错误,提示它找不到user_id
字段.
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.
可能是什么问题?
mappedBy
引用目标类中的字段.尝试在Party
类中包含一个User
字段,反之亦然.然后用@OneToOne(mappedBy="party")
注释聚会类中的用户.
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() {
...
}