[英]How to pass wildcard to Class<T> in persistance api?
I'm trying to create an abstract class, to avoid bloating code for each DAO class.我正在尝试创建一个抽象的 class,以避免每个 DAO class 的膨胀代码。
public abstract GenericDAO<T> {
public Optional<T> fetch(Long id) {
return entityManager.find(T, id)
}
}
I have tried the previous, but neither T
nor T.class
works.我已经尝试过以前的方法,但是
T
和T.class
都不起作用。 My goal is to simply have other DAOs extend this class.我的目标是简单地让其他 DAO 扩展这个 class。
How do i make this work?我如何使这项工作? As in, how do i pass the wildcard as parameter to
.find
?如中,我如何将通配符作为参数传递给
.find
?
Edit:编辑:
To better illustrate.为了更好地说明。
I have DAO for each entity.我有每个实体的 DAO。 Lets say
ADao
, BDao
.让我们说
ADao
, BDao
。 The only difference between ADao
and BDao
is a the moment the fact, that they each accept and return different type. ADao
和BDao
之间的唯一区别在于,它们各自接受和返回不同的类型。 The JPA, however, doesn't care.然而,JPA 不在乎。 Thus I want to create
AbstractDao<T>
, and have the children be ADao<EntityA>
and BDao<EntityB>
.因此,我想创建
AbstractDao<T>
,并让孩子成为ADao<EntityA>
和BDao<EntityB>
。
Thus, ADao
nor BDao
will include the repeated code, but each will work on the specific entity classes EntityA
and EntityB
(respectively).因此,
ADao
和BDao
将包含重复的代码,但每个都将在特定的实体类EntityA
和EntityB
上工作(分别)。
Maybe this is what you are looking for?也许这就是你要找的? Still not sure about your goal.
仍然不确定你的目标。
abstract class GenericDAO<T> {
public abstract Optional<T> fetch(Long id);
}
class DaoChild extends GenericDAO<YourClass>{
@Override
public Optional<YourClass> fetch(Long id) {
return entityManager.find(YourClass.class,id);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.