Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

java - Best Way to Inject Hibernate Session by Spring 3

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/>

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Spring Reference suggests this usage:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...