Entitymanager是null spring JPA配置

时间:2014-04-04 03:49:16

标签: java spring hibernate spring-mvc jpa

我一直在研究Maven + Spring + Hibernate项目。实际上,这只是一个测试项目,只是为了熟悉Spring如何使用Hibernate(+ Maven)。我已经设置并准备了必要的依赖项。例如,Spring的appcontext.xml,Hibernate的persistence.xml,JPA / Persistence / Hibernate的实体和DAO对象。

在调试期间,观察到EntityManager始终为null。我不知道是什么导致了这一点。

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
<context-param>
<param-name>patchConfigLocation</param-name>
<param-value>
        /WEB-INF/applicationContext-datasource.xml
        /WEB-INF/applicationContext.xml
        /WEB-INF/applicationContext-entity.xml          
    </param-value>
</context-param>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

应用datasource.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:jee="http://www.springframework.org/schema/jee"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
    http://www.springframework.org/schema/jee
    http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">


<jee:jndi-lookup id="datasource" jndi-name="jdbc/web"/>

<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
    <property name="persistenceXmlLocations">
        <list>
            <value>classpath*:META-INF/persistence.xml</value>
        </list>
    </property>
    <property name="defaultDataSource" ref="dataSource"/>
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitManager" ref="persistenceUnitManager"/>
    <property name="persistenceUnitName" value="wzpu"/>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

</beans>

context.xml中

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/web"
          auth="Container"
          type="javax.sql.DataSource"
          factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
          testWhileIdle="true"
          testOnBorrow="true"
          testOnReturn="false"
          validationQuery="SELECT 1"
          timeBetweenEvictionRunsMillis="30000"
          maxActive="15"
          maxIdle="10"
          minIdle="5"
          removeAbandonedTimeout="60"
          removeAbandoned="false"
          logAbandoned="true"
          minEvictableIdleTimeMillis="30000"
          jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
          username="root"
          password="root"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/names"/>
</Context>

的persistence.xml

<?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="wzpu" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.name.home.Profile</class>
    <exclude-unlisted-classes/>
    <properties>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
    </properties>
</persistence-unit>
</persistence>

Profile.java

@Entity
@Table(name = "PROFILE")
public class Profile implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "PROFILE_ID")
protected int id;

public Profile() {
    super();
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Profile other = (Profile) obj;
    if (id != other.id)
            return false;
    return true;
}

   }

ProfileDao.java

@Repository("profiledao")
public class ProfileDao {

@PersistenceContext(unitName = "wzpu")
protected EntityManager em;

@Transactional
public Profile save(Profile profile) {
    return em.merge(profile);
}
}

请帮我解决这个问题......

2 个答案:

答案 0 :(得分:2)

我认为你有

 <context:annotation-config/>

我有这个配置

<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    <qualifier value="pagTransactionManager" />
</bean>

<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    id="entityManagerFactory">
    <property name="persistenceUnitName" value="persistenceUnit" />
    <property name="dataSource" ref="dataSource" />
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    </property>
</bean>

如果在META-INF

中,则不需要指示persistence.xml的位置

也尝试使用

<param-name>contextConfigLocation</param-name>

而不是

<param-name>patchConfigLocation</param-name>

答案 1 :(得分:0)

请参阅以下内容正常。将<jpa:repositories/>(特定于Spring Data API)替换为<context:component-scan base-package="your.base.package" />

https://github.com/alanhay/spring-data-jpa-bootstrap/blob/master/src/main/resources/applicationContextRepository.xml

在默认位置假设最小的persistence.xml:

https://github.com/alanhay/spring-data-jpa-bootstrap/blob/master/src/main/resources/META-INF/persistence.xml