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

Erdinç Özdemir :

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?

buræquete :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=139578&siteId=1