Spring 3 注入 Hibernate 会话的最佳方式 [英] Best Way to Inject Hibernate Session by Spring 3

查看:19
本文介绍了Spring 3 注入 Hibernate 会话的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am not sure whats the best way to inject Hibernate's session instance to DAO classes using Spring3. I am not using Spring's Hibernate Template support for this so here is the code i have in the DAO class.

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;
}

下面是在这个方法中注入会话的代码

Below is the code for injecting session in to this method

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

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

I am not sure if this is the best way to do SessionFactory injection since we don't want to use Spring Template for our project. So any other suggestion for improvement will be much helpfull.

推荐答案

Spring 参考建议这种用法:

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.

That way your classes don't have any dependencies to Spring, you just use plain Hibernate.

这篇关于Spring 3 注入 Hibernate 会话的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆