我是Spring的新手,并试图像本文http://www.ibm.com/developerworks/library/j-genericdao/中那样实现Generic DAO。我有几个实体 - ConcreteEntity1和ConcreteEntity2。另外,我有课程
public interface GenericDao<T extends Serializable> {
public T get(long id);
public List<T> get(String hql);
public void remove(T persistentObject);
public void add(T entity);
}
和
@Repository("hibGenericDao")
public class HibGenericDaoImpl<T extends Serializable> implements GenericDao<T> {
@Autowired
private SessionFactory sessionFactory;
private Class<T> type;
public HibGenericDaoImpl(Class<T> type) {
this.type = type;
}
/** {@inheritDoc} */
@Override
public T get(long id) {
T entity;
try (Session session = sessionFactory.getCurrentSession()) {
entity = session.get(type, id);
}
return entity;
}
/** {@inheritDoc} */
@Override
public List<T> get(String hql) {
List<T> entityList;
try (Session session = sessionFactory.getCurrentSession()) {
Query query = session.createQuery(hql);
entityList = query.list();
}
return entityList;
}
/** {@inheritDoc} */
@Override
public void remove(T persistentObject) {
try (Session session = sessionFactory.getCurrentSession()) {
session.delete(persistentObject);
}
}
/** {@inheritDoc} */
@Override
public void add(T entity) {
try (Session session = sessionFactory.getCurrentSession()) {
session.saveOrUpdate(entity);
}
}
}
现在我正在尝试编写服务层,我希望自动装配HibGenericDaoImpl<ConcreteEntity1>
字段type
包含ConcreteEntity1.class
。您能否说一下如何在没有XML的情况下执行它?
答案 0 :(得分:0)
用零参数构造函数替换构造函数。然后,您可以使用this link获得带有反射的T
类型。
答案 1 :(得分:0)
如果您已经在使用spring,则可以使用GenericTypeResolver实用程序类,如本答案所示:How to get a class instance of generics type T
您应该可以执行以下操作:
this.type = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), GenericDao.class);