在JPA @OneToMany中使用泛型 [英] Use Generic in JPA @OneToMany

查看:108
本文介绍了在JPA @OneToMany中使用泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分支"课程.我想用作<的两个类字典"和链接" T>在这里.

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<>();
}

它会引发运行时异常:

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

如果我使用targetEntity=SomeEntity.class,则泛型没有任何好处. 我如何在这里使用泛型?

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

推荐答案

这是不可能的.

List<T> entities相比,这里的问题更多地是在Branch<T>声明中.当JPA提供程序从数据库中读取Branch的记录时,它将如何知道T是什么?

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?

您需要提供一个接口/超类而不是T,如果子类之间的差异很大(如您的情况),那么它只是一个空标记.

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.

这篇关于在JPA @OneToMany中使用泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆