本文介绍了从通用T派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个参数化的hibernate dao,它执行基本的crud操作,并且当参数化被用作委托来完成给定dao的基本crud操作。

  public class HibernateDao< T,ID extends Serializable>实现GenericDao< T,ID> 

我希望能够在运行时从T派生类来在Hibernate中创建条件查询,例如:

  public T findByPrimaryKey(ID id){
return(T)HibernateUtil.getSession()。load(T .getClass(),id);

$ / code>

我知道:

  T.getClass()

不存在,但有没有什么办法可以在运行时从T派生出正确的Class对象?



我已经研究过泛型和反射,但还没有提出一个合适的解决方案,也许我是缺少的东西。



谢谢。 您可以将Class作为构造函数参数传递。

  public class HibernateDao< T,ID extends Serializable>实现GenericDao< T,ID> {

私人最终课程
public HibernateDao(Class<?extends T> type){
this.type = type;
}

// ....

}


I have a parameterized hibernate dao that performs basic crud operations, and when parameterized is used as a delegate to fulfil basic crud operations for a given dao.

public class HibernateDao <T, ID extends Serializable> implements GenericDao<T, ID>

I want to be able to derive Class from T at runtime to create criteria queries in Hibernate, such that:

public T findByPrimaryKey(ID id) {
    return (T) HibernateUtil.getSession().load(T.getClass(), id);
}

I know:

T.getClass()

does not exist, but is there any way to derive the correct Class object from T at runtime?

I have looked at generics and reflection but have not come up with a suitable solution, perhaps I am missing something.

Thanks.

解决方案

You could have the Class passed as a constructor argument.

public class HibernateDao <T, ID extends Serializable> implements GenericDao<T, ID> {

    private final Class<? extends T> type;

    public HibernateDao(Class<? extends T> type) {
        this.type = type;
    }

    // ....

}

这篇关于从通用T派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:10