gpt4 book ai didi

java - 没有外键的 JPA OneToOne 关联无法正常工作

转载 作者:行者123 更新时间:2023-12-01 16:39:45 26 4
gpt4 key购买 nike

我正在使用 Hibernate/JPA,并且有 3 个表:

Contact
pk contact_id
fk member_id

Employee
pk employee_id
fk member_id

Members
pk member_id

我有:

@Entity(name = "Contact" )
public class Contact implements Serializable {

@Id
@SequenceGenerator(allocationSize = 1, name = "contact_sequence", sequenceName = "contact_ids")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "contact_sequence")
private java.lang.Long contact_id;

@OneToOne(cascade = CascadeType.ALL, targetEntity = Members.class)
@JoinColumn(name = "member_id")
private Members member;

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member", referencedColumnName = "member")
private Employee employee;

@Entity(name = "Employee")
public class Employee implements Serializable {

@Id
@SequenceGenerator(allocationSize = 1, name = "employee_sequence", sequenceName = "employee_ids")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "employee_sequence")
private java.lang.Long employee_id;

@Entity(name = "Members")
@Table(name = "Members")
public class Members implements Serializable {

@Id
@SequenceGenerator(allocationSize = 1, name = "members_sequence", sequenceName = "member_ids")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "members_sequence")
private java.lang.Long member_id;

我的问题出在Contact实体private EmployeeEmployee;上。当我启动 Jboss 服务器时:

StartException in service jboss.persistenceunit.

问题

如何在 Contact 实体上注释 private Employee 员工;

谢谢

最佳答案

您几乎正确地定义了 private Members 成员;,那么是否有理由不对 private Employee 员工; 执行相同的操作?

喜欢:

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "employee", referencedColumnName = "employee_id")
private Employee employee;

也是一个简单的link ,只是为了交叉检查整体 @JoinColumn 功能

===编辑===

看起来确实存在数据结构问题,因为从一开始关系就是ManyToOne,

如果您可以尝试以下示例:

//Employee
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "contact_id", referencedColumnName = "contact_id")
private Contact contact;

//Contact
@OneToMany(fetch = FetchType.LAZY, mappedBy = "employee_id")
private List<Employee> employees = new ArrayList<>();

然后通过选择 contact.getEmployees() 应该可以解决问题

关于java - 没有外键的 JPA OneToOne 关联无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61884640/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com