在Spring 3之前注入Hibernate会话的最佳方法

我不确定什么是使用Spring3将Hibernate会话实例注入DAO类的最佳方法。 我没有使用Spring的Hibernate Template支持,所以这里是我在DAO类中的代码。

public void setSessionFactory(SessionFactory sessionFactory){ this.sessionFactory=sessionFactory; } public SessionFactory getSessionFactory(){ log.info("Returning a refrence to the session instance"); if(sessionFactory==null){ log.error("Not able to find any associated session"); throw new RuntimeException("Not able to find any associated session"); } return sessionFactory; } 

下面是将会话注入此方法的代码

  

我不确定这是否是进行SessionFactory注入的最佳方式,因为我们不想在项目中使用Spring Template。 所以任何其他改进建议都会有所帮助。

Spring Reference建议使用此方法 :

 public class ProductDaoImpl implements ProductDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Collection loadProductsByCategory(String category) { return this.sessionFactory.getCurrentSession() .createQuery( "from test.Product product where product.category=?") .setParameter(0, category) .list(); } } 

这样你的类与Spring没有任何依赖关系,你只需使用普通的Hibernate。

skaffman的post和Sean的组合以及注释的使用。

 @Respository("productDao") public class ProductDaoImpl implements ProductDao { @Autowired private SessionFactory sessionFactory; public Collection loadProductsByCategory(String category) { return this.sessionFactory.getCurrentSession() .createQuery( "from test.Product product where product.category=?") .setParameter(0, category) .list(); } } 

XML

            product.hbm.xml     hibernate.dialect=org.hibernate.dialect.HSQLDialect     

你过度复杂了。

请不要使用那种在Hibernate文档中不断出现的糟糕的HibernateUtil模式。 Spring提供了一种更好,更好的配置Hibernate SessionFactoryLocalSessionFactoryBean ( 参见docs for example usage )。

LocalSessionFactoryBean生成一个SessionFactory对象,您可以将其作为属性注入DAO bean。

Spring很高兴您不使用HibernateDaoSupportHibernateTemplate – 有一部分文档解释了如何很好地完成它。

使用Hibernate的可行方法是通过JPA(hibernate-entitymanager):

 @PersistenceContext private EntityManager entityManager; 

并在applicationContext.xml

              

你需要一个META-INF/persistence.xml