Erdinç Özdemir
Erdinç Özdemir

Reputation: 1381

JPA - How to use @OneToMany mappedBy property for different fields in a generic structure?

I have two related entity objects.

Class A inherits from generic Base class.

@Entity
public class A extends Base<B> {

}

@Entity
public class B {

    @ManyToOne(cascade = CascadeType.ALL)
    private A a;

}

Similar for class C;

@Entity
public class C extends Base<D> {

}

@Entity
public class D {

    @ManyToOne(cascade = CascadeType.ALL)
    private C c;

}

with Base class;

@Entity
public class Base<T> {

    @OneToMany(mappedBy = "{both a & c here?}", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    Set<T> set;
}

How can I make mappedBy property on the Base support two different values?

Upvotes: 6

Views: 775

Answers (1)

bur&#230;quete
bur&#230;quete

Reputation: 14688

How about renaming both @ManyToOne annotated parent fields with the same name?

@ManyToOne(cascade = CascadeType.ALL)
private A parent;

and

@ManyToOne(cascade = CascadeType.ALL)
private C parent;

then you can have;

@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
Set<T> set;

for you cannot pass a non-constant value as an annotation parameter.

Upvotes: 5

Related Questions