在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 SessionFactory
– LocalSessionFactoryBean
( 参见docs for example usage )。
LocalSessionFactoryBean
生成一个SessionFactory
对象,您可以将其作为属性注入DAO bean。
Spring很高兴您不使用HibernateDaoSupport
和HibernateTemplate
– 有一部分文档解释了如何很好地完成它。
使用Hibernate的可行方法是通过JPA(hibernate-entitymanager):
@PersistenceContext private EntityManager entityManager;
并在applicationContext.xml
:
你需要一个META-INF/persistence.xml
- javagenerics类型参数和对这些类型的操作
- Criteria Builder在Select语句中创建新对象
- java.lang.ClassCastException:[Ljava.lang.Object; 无法强制转换为className
- Hibernate + SQLite没有创建数据库
- Hibernate合并
- 值’0000-00-00’不能表示为java.sql.Date
- 在playframework的子模块中添加jpa / hibernate @Entity到实体管理器进行扫描
- 使用Spring Boot + Hibernate + MySql运行MVC应用程序
- 使用Hibernate将java.util.Date持久化到MySql中的问题