我会走向不同的方向。我会使用 JPA 并将休眠设置为 JPA 供应商。它看起来会有点不同,但是 Spring 完全支持 JPA(包括事务管理器和所有东西)。它看起来像这样:
而不是 hibernate.cfg.xml,您将有一个名为“persistence.xml”的 xml(将驻留在资源/META-INF 中),它看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="myPersistanceUnit">
<class>com.company.entities.Entity1</class>
<class>com.company.entities.Entity2</class>
<class>com.company.entities.Entity3</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
您的 ApplicationContext.xml 将具有以下内容:
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<!-- The data source is configured in the application server but spring also supports a configured bean -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/MyDataSource" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="myPersistanceUnit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.DerbyDialect" />
</bean>
</property>
</bean>
代替休眠注释,您将使用 JPA 注释(基本相同 - 在 javax.persistence 包下)并且您的基本 dao 调用将使用
@PersistenceContext
protected EntityManager entityManager;
处理数据库操作。在这些配置下,我认为您不会有任何问题。