简体   繁体   English

双向OneToOne中的相同实体

[英]Same Entity in Bidirectional OneToOne

I'm trying to find a solution about this problem: I have a relationship table that map the rules of another entity. 我正在尝试找到有关此问题的解决方案:我有一个关系表,该关系表映射了另一个实体的规则。

    @Entity
public class Relation {
   @Id
   public Long id;
   @OneToOne
   public Address addressHome;
   @OneToOne
   public Address addressWork
}

and a class Address 和一个班级地址

@Entity
    public class Address {
       @Id
       public Long id;
    }

I would put a bidirectional relation from Address to relation. 我会把双向关系从地址到关系。

Can someone help me? 有人能帮我吗? Thanks 谢谢

What you need to do is telling Hibernate the relation between Address and Relation : first you need to implement this into Relation: 您需要做的就是告诉Hibernate AddressRelation之间的Relation :首先,您需要将其实现到Relation中:

@Entity
public class Relation {
    @Id
    public Long id;

    @OneToOne
    @JoinColumn(name = "addressHome", referencedColumnName = "id")
    public Address addressHome;

    @OneToOne
    @JoinColumn(name = "addressWork", referencedColumnName = "id")
    public Address addressWork;
}

Then you need to edit your Address class like this: 然后,您需要像这样编辑Address类:

@Entity
public class Address {
   @Id
   public Long id;

   @OneToOne(mappedBy = "addressHome")
   public Relation relationHome;

   @OneToOne(mappedBy = "addressWork")
   public Relation relationWork;
}

If you prefer you can put the annotations on getter instead on variable. 如果愿意,可以将注释放在getter上,而不是放在变量上。

I don't have enough reputation to comment, but assuming this is all that you have in your code, It should work in that way, maybe you are forgetting the @JoinColumn label specifying the name of the database fields. 我没有足够的声誉来评论,但是假设这就是您在代码中拥有的全部,它将以这种方式工作,也许您忘记了指定数据库字段名称的@JoinColumn标签。 I suggest to put more information about how your data model is related. 建议您提供有关您的数据模型如何关联的更多信息。

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

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