在通用 Spring CRUD DAO 中获取正确的 Hibernate 模板
题
我对 Spring 还很陌生,而且我发现制作所有这些 CRUD DAO 很烦人,所以我制作了一个“公共类 GenericCRUDDAO 扩展 HibernateDaoSupport 实现 CRUDDAO”。在我的服务对象中,我简单地说
private GenericCRUDDAO<User, Integer> userDAO = new GenericCRUDDAO<User, Integer>();
我不再需要编写简单的 DAO 并将它们连接起来。耶!除了一件事之外,我相信所有有经验的 Spring 开发人员都会立即看到:我无法在 GenericCRUDDAO 中获取 Hibernate 模板,所以这样做
HibernateTemplate ht = getHibernateTemplate();
给我一个空的ht。不太好。我想将其连接起来,这意味着制作一个通用的CRUDDAO bean,然后设置一个静态的AnnotationSessionFactoryBean,但这仍然不会给我一个HibernateTemplate。关于如何解决这个问题以便我可以拥有我的 Hibernate 模板有什么建议吗?
我还应该考虑制作通用 CRUD DAO 的更多问题吗?
干杯
尼克
解决方案
对于许多人来说, HibernateTemplate
和 HibernateDaoSupport
都在出局,而是首选注入 SessionFactory
。不是每个人,请注意,但这是我不久前采用的趋势,从我自己的通用DAO中删除 HibernateTemplate
。
这篇博客有一个很好的总结。
作者的例子应该能够帮助你达到你想要的目标。
其他提示
通用Dao
嗯,对我来说, 如果您的 GenericDAO 是“通用”的,那么您可能只需要一个实例, ,并用该单个实例完成所有操作。
我确信你不会因为实例而烦恼,而是在重复时你会生气(我同意你的观点)。
例如, 您可以将实体类传递给通用方法.
- 公共无效保存(类,E ...):允许您保存一个或多个 E 类型实例,E 是您的实体之一。
- 公共E负载(类,长ID):加载一个实体。
...
/** Assuming the entities have a superclass SuperEntity with getIdent(). */ public class GenericDaoImpl implements GenericDao { /** Save a bunch of entities */ public void save(SuperEntity... entities) { for(SuperEntity entity : entities) { getSession().save(entity); } } /** Load any entity. */ public <E extends SuperEntity> E load(Class<E> entityClass, Long ident) { return (E)getSession().load(entityClass, ident); } // other generic methods }
变体
在我们的应用程序中,我们实际上有一个变体。因为我们对每个 Dao 有很多特定的请求,所以无论如何我们都需要特定的 Dao 类(创建类并连接它),因此为了避免无法定义 Dao 的特殊情况,我们立即创建特定的 Dao 类。
编码
但我们绝不会重复代码。我们所有的 Daos 都扩展了 GenericDao,在构造函数中提供了所需的 Class 参数。示例代码(不完整,简单了解基本思想):
public abstract class GenericDaoImpl<E extends SuperEntity>
implements GenericDao<E> {
/** Available for generic methods, so it is not a parameter
* for the generic methods. */
private final Class<E> entityClass;
protected GenericDaoImpl(Class<E> entityClass) {
this.entityClass = entityClass;
}
// generic implementation ; can be made efficient, as it may
// send the orders as a batch
public void save(E... entities) {
for(SuperEntity entity : entities) {
getSession().save(entityClass, entity.getIdent());
}
// possibly add flushing, clearing them from the Session ...
}
// other generic methods
}
public class PersonDaoImpl extends GenericDaoImpl<Person>
implements PersonDao {
/** Constructor, instanciating the superclass with the class parameter. */
public PersonDaoImpl() {
super(Person.class);
}
/** Specific method. */
public List<Person> findByAge(int minAge, int maxAge) {
//....
}
}
接线
连接所有的豆子并不是致命的。现在自动装配的策略有很多,你不用担心。春天见他们
http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config