Hibernate中两个OneToMany设置为同一表

时间:2018-08-02 10:06:55

标签: hibernate jpa spring-data-jpa

我有一个用户表,以及一个用户之间的通话表。

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的详细信息以及其他字段(标识等)。

每个呼叫涉及一个呼叫者和一个被呼叫者。每个用户可以拨打和接听许多电话。

简单地说:上面的JPA有效使用方法是,特别是休眠吗?

1 个答案:

答案 0 :(得分:0)

没有主键就不能拥有休眠类。此外,您应该使用property-based acccess而不是field-based access,否则休眠将给您带来编译时错误。您的代码应为:

@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