[英]Getting the correct Hibernate template in a generic Spring CRUD DAO
我對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
。
這個博客有一個很好的總結。
作者的例子應該能夠幫助您到達想要的地方。
好吧,對我來說, 如果您的GenericDAO是'generic',那么您可能只需要一個實例 ,並使用該單個實例完成所有操作。
我確信它不會打擾您,例如,反復發脾氣(我也同意)。
例如, 您可以將Entity類傳遞給通用方法 。
...
/** 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.