无法使用Spring托管的EntityManager保留数据

时间:2017-05-02 18:23:44

标签: java spring hibernate jpa

我再次需要你的帮助,我正在尝试在我的独立java应用程序中集成Hibernate + Spring,但是数据库操作不起作用,但是我注入了通过调试验证的entitymanager,所以我不确定缺少什么我的代码/配置,我通过谷歌搜索做了一些研究,但没有找到解决我的问题的东西。所以我发布了我的代码/配置,以便有人可以帮助我解决这个问题。

实体类:

      package com.entity;

      import javax.persistence.Column;
      import javax.persistence.Entity;
      import javax.persistence.GeneratedValue;
      import javax.persistence.GenerationType;
      import javax.persistence.Id;
      import javax.persistence.Table;

      @Entity
      @Table(name = "employee")
      public class Employee {

               @Id
               @GeneratedValue(strategy =  GenerationType.AUTO)
               @Column(name = "EMP_ID")
               private Integer empoyeeId;

               @Column(name = "EMP_NAME")
               private String employeeName;

               public Integer getEmpoyeeId() {
                     return this.empoyeeId;
               }

               public void setEmpoyeeId(Integer empoyeeId) {
                     this.empoyeeId = empoyeeId;
               }

               public String getEmployeeName() {
                     return this.employeeName;
               }

               public void setEmployeeName(String employeeName) {
                   this.employeeName = employeeName;
               }
       }

dao类

  package com.dao.impl;

  import javax.persistence.EntityManager;

  import com.dao.IEmployeeDao;
  import com.entity.Employee;

  public class EmployeeDao implements IEmployeeDao {

        private static final Logger LOGGER = 
                  LogManager.getLogger(EmployeeDao.class);

        @PersistenceContext(unitName = "testPU")
        private EntityManager em;

        @Override
        public Employee create(Employee aEmployee) {
           return this.em.merge(aEmployee);
        }

        @Override
        public Employee fetchEmployeeById(Integer aEmployeeId) {
         return this.em.find(Employee.class, aEmployeeId);
        }
  }

主要班级:

    package com.client;

    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    import com.dao.IEmployeeDao;
    import com.entity.Employee;

    public class Client {
           private static final Logger LOGGER = LogManager.getLogger(Client.class);

           public static void main(String[] args) throws BeansException, 
                   Exception {
                   ApplicationContext applicationContext = new 
                   ClassPathXmlApplicationContext("applicationcontext.xml");
                   LOGGER.info("client invoked");
                   IEmployeeDao employeeDao =  
                   (IEmployeeDao)applicationContext.getBean("employeeDao");
                   Employee employee = new Employee();
                   employee.setEmployeeName("Suraj Kumar");
                   employee = employeeDao.create(employee);
                   employee =                        
                   employeeDao.fetchEmployeeById(employee.getEmpoyeeId());  
                   //getting null pointer here as employee is null

                   //       EntityManagerFactory emf = 
                           Persistence.createEntityManagerFactory("testPU");
                  //        EntityManager em = emf.createEntityManager();
                  //        em.getTransaction().begin();
                  //        EmployeeDao employeeDao = new EmployeeDao();
                  //        employeeDao.setEm(em);
                  //        Employee employee = new Employee();
                  //        employee.setEmployeeName("Suraj Kumar");
                  //        employee = employeeDao.create(employee);
                  //        employee = 
                    employeeDao.fetchEmployeeById(employee.getEmpoyeeId());
                  //        em.getTransaction().commit();
                  //        em.close();
                  //        emf.close();
          }
     }

使用上面的客户端代码当尝试通过id获取employee时,我得到空指针异常,因为对create的调用返回的员工返回null,断言记录没有持久化。

然而,当我通过评论上面的未注释代码关闭spring并取消注释现在注释的那些,即当我只使用没有spring的hibernate时,一切正常。我在下面提供了配置文件。

的applicationContext.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:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd ">
    <import resource="aspects.xml"/>

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

        <bean id="myEmf" 
        class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
            <property name="persistenceUnitName" value="testPU"/>
        </bean>

        <bean id="employeeDao" class="com.dao.impl.EmployeeDao" />

    </beans>

的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="testPU" transaction-type="RESOURCE_LOCAL">
   <provider>org.hibernate.ejb.HibernatePersistence</provider>
   <class>com.entity.Employee</class>
   <exclude-unlisted-classes>true</exclude-unlisted-classes>
   <properties>
      <property name="hibernate.connection.url" 
                value="jdbc:mysql://localhost:3306/dbname"/>
      <property name="hibernate.connection.driver_class" 
                value="com.mysql.jdbc.Driver"/>

      <property name="hibernate.dialect" 
                value="org.hibernate.dialect.MySQLDialect"/>
      <property name="hibernate.connection.username" value="user"/>
      <property name="hibernate.connection.password" value="password"/>
      <property name="hbm2ddl.auto" value="update"/>
      </properties>
  </persistence-unit>
  </persistence>

我也在使用方面,但我还没有发布代码,因为我不确定它是否相关,因为我试图通过关闭方面,即使那时我面临这个问题,只是一个奇怪的事情发生在关闭方面,而不是获取空指针异常我从EntityManager类的find方法中获取另一个异常,这表明在这种情况下dao类的create方法不返回null。

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

您的交易似乎没有被提交。

尝试将@Transactional添加到EmployeeDao类中的方法中,或者更好的是,创建一个Service层来处理事务并注释其方法whit @Transactional