gpt4 book ai didi

hibernate - 两个 OneToMany 集合到 Hibernate 中的同一个表

转载 作者:行者123 更新时间:2023-12-05 07:31:44 25 4
gpt4 key购买 nike

我有一张用户表和一张用户之间的通话表。

public class User {

@Id
@Column(name="userId")
private long userId;

@OneToMany(mappedBy="caller")
Set<Call> madeCalls;

@OneToMany(mappedBy="callee")
Set<Call> receivedCalls;

}

public class Call {

@ManyToOne
@JoinColumn(name="calleeId", referencedColumnName="userId")
User callee;

@ManyToOne
@JoinColumn(name="callerId", referencedColumnName="userId")
User caller;

}

为简洁起见,省略了 getter 和 setter 以及其他字段(id 等)等详细信息。

每次调用都涉及一名调用者和一名被调用者。每个用户都可以调用和接听许多电话。

简单地说:以上是 JPA 的有效使用,特别是 hibernate?

最佳答案

没有主键就无法拥有 hibernate 类。此外,您应该使用property-based acccess 而不是field-based access 否则hibernate 会给您编译时错误。您的代码应该是:

@Entity
@Table(name="user")
public class User {

@Id // use all these annotation in the getter method
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(name = "native", strategy = "native")
private long userId;

@OneToMany(mappedBy="caller") // use this annotation in the getter method
private Set<Call> madeCalls;

@OneToMany(mappedBy="callee") // use this annotation in the getter method
private Set<Call> receivedCalls;

}

@Entity
@Table(name="call")
public class Call {

@Id // use all these annotation in the getter method
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(name = "native", strategy = "native")
private long callId;

@ManyToOne
@JoinColumn(name="calleeId") // use this annotation in the getter method
private User callee;

@ManyToOne
@JoinColumn(name="callerId") // use this annotation in the getter method
private User caller;

}

Here is a very good tutorial for hibernate and performance .

关于hibernate - 两个 OneToMany 集合到 Hibernate 中的同一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51650881/

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