简体   繁体   English

如何与JPA一对一地将实体A映射到实体B两次?

[英]How to map Entity A to Entity B twice in a one to one relation with JPA?

So nothing I tried seems to work. 因此,我尝试过的所有方法似乎都无效。 I would like to have something like this: 我想要这样的东西:

class A {    
    B foo;
    B bar;
}

class B {
    A baz;
}

What I tried in class A is as follows: 我在A类中尝试的内容如下:

@OneToOne(targetEntity = B.class)
@JoinColumn(name = "foo_id")
@Cascade(CascadeType.ALL)
public B getFoo() {
    return foo;
}

@OneToOne(targetEntity = B.class)
@JoinColumn(name = "bar_id")
@Cascade(CascadeType.ALL)
public B getBar() {
    return bar;
}

which does not seem to work. 这似乎不起作用。 I always end up where foo_id and bar_id is same for a reason I do not understand. 由于我不明白的原因,我总是以foo_id和bar_id相同的地方结束。

So when I inspect table "A" in my DB for row with id 1, I would like to have: 因此,当我在数据库中检查表“ A”中ID为1的行时,我希望拥有:

foo_id = 1
bar_id = 2

and in Table B, I should have 2 entities with id 1 and 2, where both have baz_id = 1; 在表B中,我应该有2个ID为1和2的实体,两个实体的baz_id = 1;

Is baz_id intended to be a FK back to A? baz_id是否打算作为FK返回A? Because I think the database mapping to model is wrong in that case. 因为我认为在这种情况下数据库到模型的映射是错误的。 You've already established the FK relationship from the PK of B to either A.foo_id or A.bar_id. 您已经建立了从B的PK到A.foo_id或A.bar_id的FK关系。

Also be careful with your cascading rules on a relationship like this. 在这种关系上的级联规则也要小心。 SQL Server will reject two FKs to the same table unless the DB action for cascading is "no action". 除非用于级联的DB操作为“无操作”,否则SQL Server将拒绝同一表的两个FK。

I do happen to know that what you're trying to do is possible in JPA, since I just recently did it on an entity myself: 我确实知道您要尝试做的事在JPA中是可能的,因为我最近刚在一个实体上做到了:

@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
@JoinColumn(name = "portal_logo_id", referencedColumnName = "id", nullable = true)
private PortalResourceModel logo;

@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
@JoinColumn(name = "portal_favicon_id", referencedColumnName = "id", nullable = true)
private PortalResourceModel favicon;

I also don't have a mapping in PortalResourceModel for logo or favicon, because that side of the relationship doesn't know how it is being used. 我也没有在PortalResourceModel中为徽标或Favicon映射,因为关系的那一侧不知道它是如何使用的。 And I can't have a generic mapping from multiple relationships on the owning side to a single relationship on the mappedBy side. 而且,我无法从拥有方的多个关系到mappingBy方面​​的单个关系进行通用映射。

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

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