简体   繁体   English

JPA多对多自引用关系与附加专栏

[英]JPA many to many self referencing relation with additional column

I am working with JPA and use Hibernate as a provider to my SQL Server database. 我正在使用JPA,并将Hibernate用作SQL Server数据库的提供程序。

I need a many-to-many self referencing relation that has an additional column or even more additional columns. 我需要一个多对多自引用关系,该关系具有一个附加列或什至更多附加列。

That is my current code. 那是我当前的代码。 I am getting exceptions by Hibernate: 我正在通过Hibernate获得例外:

@Entity
public class Person {
  @OneToMany(cascade = CascadeType.ALL, mappedBy = "person", fetch = FetchType.EAGER)
  private Set<Relation> relations;

  @OneToMany(cascade = CascadeType.ALL, mappedBy = "relPerson", fetch = FetchType.EAGER)
  private Set<Relation> inverseRelations;
}

@Entity
public class Relation implements Serializable {
  @Id
  @ManyToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER)
  @PrimaryKeyJoinColumn(name = "PersonID", referencedColumnName = "id")
  private Person person;

  @Id
  @ManyToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER)
  @PrimaryKeyJoinColumn(name = "RelPersonId", referencedColumnName = "id")
  private Person relPerson;
}

During runtime i get an exception from hibernate: 在运行时,我从休眠中得到一个异常:

org.hibernate.TransientObjectException: object references an unsaved transient instance

Is there any way to implement this a little bit more intelligent and nicely?? 有什么办法可以更智能,更好地实现这一点吗? Without getting that exception. 没有得到那个例外。

Thanks, ihrigb 谢谢,ihrigb

If an object not associated with a Hibernate Session , the object will be Transient . 如果某个对象与Hibernate Session不关联,则该对象将是Transient

An instance of Relation list may be Transient (Normally, There is no identifier value for that instance) when you save Person . 保存Person时, Relation列表的实例可能是Transient (通常,该实例没有标识符值)。

Here is better way to understand object state. 是了解对象状态的更好方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM