我正在尝试设置一个用于部署到Glassfish的Spring JPA Hibernate简单示例WAR。 我看到一些示例使用persistence.xml文件,而其他示例则不是这样做。 有些示例使用dataSource,而有些则不使用。目前我的理解是,如果我拥有:
<persistence-unit name="educationPU"
transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.coe.jpa.StudentProfile</class>
<properties>
<property name="hibernate.connection.driver_class"
value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/COE" />
<property name="hibernate.connection.username" value="root" />
<property name="show_sql" value="true" />
<property name="dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
我可以成功部署,但是我的EntityManager没有被Spring注入。我的applicationContext.xml:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="educationPU" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="StudentProfileDAO" class="com.coe.jpa.StudentProfileDAO">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="studentService" class="com.coe.services.StudentService">
</bean>
我的带有 EntityManager 的类:
public class StudentService {
private String saveMessage;
private String showModal;
private String modalHeader;
private StudentProfile studentProfile;
private String lastName;
private String firstName;
@PersistenceContext(unitName="educationPU")
private EntityManager em;
@Transactional
public String save()
{
System.out.println("*** em: " + this.em); //em is null
this.studentProfile= new StudentProfile();
this.saveMessage = "saved";
this.showModal = "true";
this.modalHeader= "Information Saved";
return "successs";
}
我的web.xml文件:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
我是否遗漏了某些部分,才能使Spring注入到StudentService中的“em”?
@PersistenceContext
的可选属性name
用于查找注入的实体管理器,但是它在persistence.xml
中没有对应的元素。如果这对你有效,那么我认为这只是与缺少unitName
相关的幸运副作用(这种情况下的行为是供应商特定的)。但这是不正确的。 - Pascal Thivent