春季3之前注入休眠会话的最佳方法 3

2022-09-02 02:13:26

我不确定使用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;
}

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

<bean id="genericSessionFactory" class="HibernateSessionFactory"
        factory-method="getSessionfactory" scope="prototype/>

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


答案 1

春季参考建议使用这种用法

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。


答案 2

skaffman的帖子和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

<beans>

  <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
    <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>
  </bean>

  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="mappingResources">
      <list>
        <value>product.hbm.xml</value>
      </list>
    </property>
    <property name="hibernateProperties">
      <value>
        hibernate.dialect=org.hibernate.dialect.HSQLDialect
      </value>
    </property>
  </bean>

</beans>

推荐