Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

hibernate - Spring 3 Annotations - HibernateDaoSupport - Repository Requires Session Factory

I am getting an exception saying :

java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required

When trying to use the @Repository annotation on a HibernateDaoSupport class. The error message is straightforward, in order to create the Repository it needs a sessionFactory. However,I have defined a session factory in my XML:

<!-- Hibernate -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dashDataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.mycomp.myapp.Category</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            </props>
        </property>
    </bean>

So I'm not sure how to give the repository the SessionFactory that it requires while it's creating it's annotation driven beans, I attempted to do the following:

 @Autowired
    protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {
        return super.createHibernateTemplate(sessionFactory);
    }

But this does not solve the problem, likely because the repository needs that property while instantiating, not just when performing an action. Unfortunately, I don't know how to get around this problem because there are no constructors or initialization methods to override with a @Autowired annotation.

I checked to make sure the sessionFactory bean is being created and can be Autowired, and that is fine.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

HibernateDaoSupport is supplied with SessionFactory via setSessionFactory(). However, setSessionFactory() is final, so you can't override it to add an @Autowired annotation. But you can apply @Autowired to the arbitrary method and call setSessionFactory() from it:

@Autowired
public void init(SessionFactory factory) {
    setSessionFactory(factory);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...