我有一个单元测试java类文件,我需要使用Spring和Hibernate。
这是模块的顶部:
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations={"classpath:server-data-config.xml"})
@Transactional
public class MyTest {
// Other code follows
如您所见,我从server-data-config.xml
加载Spring的上下文配置它包含以下需要会话工厂的配置:
<bean id="txnManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
现在我在会话工厂得到以下期望:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
那是因为我的会话工厂是在hibernate.cfg.xml中定义的,我没有做任何事情来加载它:
<hibernate-configuration>
<session-factory>
Some stuff here
</session-factory>
</hibernate-configuration>
我应该在单元测试java类中添加一些注释来读取hibernate.cfg.xml吗?我该如何解决此异常?
答案 0 :(得分:0)
你必须在你的xml中指定可以找到hibernate配置的地方
spring config:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>file:src/hibernate.cfg.xml</value> // your hibernate.cfg.xml location
</property>
</bean>
你可以在java中采用这种方法:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration()
.configure().buildSessionFactory();
} catch (Throwable ex) {
// Log exception!
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession()
throws HibernateException {
return sessionFactory.openSession();
}
}
因为后一种方法你有sessionfactory,你可以这样配置它:
SessionFactory sessionFactory = new Configuration()
.configure("/persistence/hibernate.cfg.xml")
.buildSessionFactory();