在JPA和Hibernate中创建外键约束 [英] Creating a foreign key constraint in JPA and Hibernate

查看:138
本文介绍了在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() {
  ...
}

这篇关于在JPA和Hibernate中创建外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆