开发者

Hibernate: Multiple FK relationships

开发者 https://www.devze.com 2023-01-27 09:51 出处:网络
I\'m kinda stuck defining a Hibernate Entity: Assuming I have the following two tables in a 开发者_如何学Cdatabase:

I'm kinda stuck defining a Hibernate Entity:

Assuming I have the following two tables in a 开发者_如何学Cdatabase:

(A)

  • fromCompany
  • toCompany
  • viaCompany

(B)

  • companyID (PK)
  • description

where the elements of (A) point to the primary key of (B); so there are 3 one-to-one relationships between the FKs and the PK. I assume 3 OneToOne statements with different mappedBy conditions are not the way to go, mh? Has been a long day - I probably just don't get it ;)

Thanks for your help!


If I understood correctly, you want your database to look like this:

tableA
- id
- fromCompanyId (references tableB.id)
- toCompanyId (references tableB.id)
- viaCompanyId (references tableB.id)

tableB
- id
- description

If so, you can certainly have this. You just need to override the default column name for the relationship, so that each association have it's own column name instead of falling back to the default name, which would render the three associations with the same name, causing problems.

I don't really agree with OneToOne, but I assume this was a conscious decision.

See this: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-association


You certainly can do this with one-to-one relationships. You would have three Company objects in your A class, and appropriate mappings.

It would help if we could see the code and the hibernate mappings.


The easiest way to implement Class A with 3 ManyToOne Relationships pointing to ClassB

@Entity
class ClassA {

    //@ID
    //private id;

    @ManyToOne
    private ClassB from;

    @ManyToOne
    private ClassB toCompany;

    @ManyToOne
    private ClassB viaCompany;
}

would not work, because every entity needs an Id. – You could try to overcome this problem by using a combinded Id (consisting of the three associations), but I guess it results in a lot of trouble to implement a ID consisting of associations to other entities.

@see Hibernate/persistence without @Id

The other way provided by Hibernate are so called Ternary Associations. – In this case you model the complete table A in form of an ternary m:n relationship. – But this is a very complicated task too.

@see http://docs.jboss.org/hibernate/core/3.5/reference/en/html/collections.html#collections-ternary

0

精彩评论

暂无评论...
验证码 换一张
取 消