如何在定义持久性单元时注入SessionFactory?

时间:2016-01-19 11:15:20

标签: java spring hibernate

我有一个完全可用的Spring 4 + Hibernate应用程序。 Hibernate是通过<persistence-unit>配置的......我的单元测试可以毫无问题地完成所有与数据库相关的工作。但现在我想访问Hibernate会话;要做到这一点,我应该注入SessionFactory。如何注入它考虑以下配置?

我知道我可以定义像LocalSessionFactoryBean这样的bean但不知道如何配置它。 (我也不希望重复配置。)

MyTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:META-INF/spring/test-context.xml" })
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class})
public class MyTest {

    @Inject
    SessionFactory sessionFactory; // want it injected

}

测试context.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    <context:annotation-config/>
    <context:component-scan base-package="com.mycompany"/>
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="hibernateJpaVendorAdapter"
          class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
        <property name="persistenceUnitName" value="my-persistence-unit"/>
    </bean>
</beans>

的persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="..." version="2.0">
    <persistence-unit name="my-persistence-unit" transaction-type="JTA">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:jboss/datasources/my</jta-data-source>
        <class>com.mycompany.entity.Document</class>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="validate"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="false"/>
            <property name="hibernate.archive.autodetection" value="class, hbm"/>
            <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>
        </properties>
    </persistence-unit>
</persistence>

1 个答案:

答案 0 :(得分:0)

因为我使用JPA,我应该注入EntityManager,而不是SessionFactory。这终于解决了我的任务。

@PersistenceContext
private EntityManager entityManager;
...
entityManager.refresh(obj); // working with H-session
...

这正是@ m-deinum的评论;如果他将添加他自己的答案,那么我将其标记为决定。