简体   繁体   中英

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:

@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.

So when I inspect table "A" in my DB for row with id 1, I would like to have:

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;

Is baz_id intended to be a FK back to 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.

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".

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:

@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. And I can't have a generic mapping from multiple relationships on the owning side to a single relationship on the mappedBy side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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