barbariania
barbariania

Reputation: 549

Use Generic in JPA @OneToMany

I have a class "Branch". Either classes "Dictionary" and "Link" which I want to use as < T> here.

@Entity
public class Branch<T> {
   ...
   @OneToMany(mappedBy = "branch", orphanRemoval = true, cascade = CascadeType.ALL)
   private List<T> entities = new ArrayList<>();
}

It throws a Runtime Exception:

org.hibernate.AnnotationException: Property by.ipps.accounting.model.Branch.branches has an unbound type and no explicit target entity. Resolve this Generic usage issue or set an explicit target attribute (eg @OneToMany(target=) or use an explicit @Type

If I use targetEntity=SomeEntity.class there is no benefits of generic. How can I use generics here?

Upvotes: 5

Views: 2958

Answers (1)

Dragan Bozanovic
Dragan Bozanovic

Reputation: 23552

This is not possible.

The issue here is more in Branch<T> declaration than in List<T> entities. When JPA provider reads the record of Branch from database, how would it know what T is?

You would need to provide an interface/superclass instead of T, be it only an empty marker one if the differences between subclasses are large as in your case.

Upvotes: 2

Related Questions