无法在JPA + Spring中保持实体,没有错误

时间:2015-12-08 06:08:48

标签: java mysql spring hibernate jpa

我试图将实体持久化到JAP + Spring但它没有将数据插入到数据库中,没有显示错误。当我在服务器上部署我的项目时,我的表是在DB中自动创建的,当我手动将数据插入数据库并尝试获取它时,它成功地从数据库中获取数据,但是在插入数据时它不会给出任何数据错误也不会将其插入数据库中。下面是我的代码请帮忙。 的的web.xml

<display-name>Spring MVC Application</display-name>
    <servlet>
      <servlet-name>HelloWeb</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/HelloWeb-servlet.xml,/WEB-INF/servlet-context.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>HelloWeb</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>

servlet的context.xml中

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

    <context:component-scan base-package="com.demo" />
    <mvc:annotation-driven />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

的HelloWeb-servlet.xml中

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

    <context:annotation-config />
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/demodb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="rahul"></property>
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceUnitName" value="JPA_Demo" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
                <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
            </bean>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"></property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />    
</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="JPA_Demo" transaction-type="RESOURCE_LOCAL">
        <class>com.data.entity.Employee</class>

        <properties>
         <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/demodb"/>
         <property name="javax.persistence.jdbc.user" value="root"/>
         <property name="javax.persistence.jdbc.password" value="rahul"/>
         <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.ddl-generation" value="create-tables"/>
      </properties>

    </persistence-unit>
</persistence>

EmployeeRESTController.java

@Controller
public class EmployeeRESTController {

    @Autowired
    private CreateEmployeeDao createEmployeeDao;    

    @RequestMapping(value = "/employee/create")
    public @ResponseBody String getCreateEmployees() {
        this.createEmployeeDao.createEmployee();
        return "Success";
    }

    @RequestMapping(value = "/employee/get")
    public @ResponseBody Employee getGetEmployees() {
        return this.createEmployeeDao.findEmployeeBySalary(40000);
    }
}

CreateEmployeeDao.java

@Repository
@Transactional(value = "transactionManager", propagation = Propagation.REQUIRED)
public class CreateEmployeeDao {

    @PersistenceContext(name = "entityManagerFactory", unitName = "JPA_Demo")
    private EntityManager em;

    public void createEmployee() {            
        Employee employee = new Employee();
        // employee.setEid(1290);
        employee.setEname("Gopal");
        employee.setSalary(40000);
        employee.setDeg("Technical Manager");            
        em.persist(employee);    
        // em.flush();
    }

    public Employee findEmployeeBySalary(double salary) {
        Query q = em.createNamedQuery("find employee by salary");        
        q.setParameter("salary", salary);        
        return (Employee) q.getSingleResult();
    }
}

Employee.java

@Entity
@Table
@NamedQueries({
        @NamedQuery(query = "Select e from Employee e where e.eid = :id", name = "find employee by id"),
        @NamedQuery(query = "Select e from Employee e where e.salary = :salary", name = "find employee by salary") })
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int eid;
    private String ename;
    private double salary;
    private String deg;

    public Employee(int eid, String ename, double salary, String deg) {
        super();
        this.eid = eid;
        this.ename = ename;
        this.salary = salary;
        this.deg = deg;
    }

    public Employee() {
        super();
    }

    public int getEid() {
        return eid;
    }

    public void setEid(int eid) {
        this.eid = eid;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String getDeg() {
        return deg;
    }

    public void setDeg(String deg) {
        this.deg = deg;
    }
}
当我点击插入数据的请求

时,

下面是我的服务器日志

11:31:57,315 DEBUG [org.springframework.web.servlet.DispatcherServlet] (http-/0.0.0.0:8080-1) DispatcherServlet with name 'HelloWeb' processing GET request for [/springrestexample/employee/create]
11:31:57,398 DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] (http-/0.0.0.0:8080-1) Looking up handler method for path /employee/create
11:31:57,473 DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] (http-/0.0.0.0:8080-1) Returning handler method [public java.lang.String com.demo.controller.EmployeeRESTController.getCreateEmployees()]
11:31:57,562 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] (http-/0.0.0.0:8080-1) Returning cached instance of singleton bean 'employeeRESTController'
11:31:57,566 DEBUG [org.springframework.web.servlet.DispatcherServlet] (http-/0.0.0.0:8080-1) Last-Modified value for [/springrestexample/employee/create] is: -1
11:31:57,952 DEBUG [org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler] (http-/0.0.0.0:8080-1) Creating new EntityManager for shared EntityManager invocation
11:31:58,063 DEBUG [org.hibernate.impl.SessionImpl] (http-/0.0.0.0:8080-1) opened session at timestamp: 14495545180
11:31:58,180 DEBUG [org.hibernate.event.def.AbstractSaveEventListener] (http-/0.0.0.0:8080-1) delaying identity-insert due to no transaction in progress
11:31:58,205 DEBUG [org.springframework.orm.jpa.EntityManagerFactoryUtils] (http-/0.0.0.0:8080-1) Closing JPA EntityManager
11:32:01,225 DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor] (http-/0.0.0.0:8080-1) Written [Success] as "text/html" using [org.springframework.http.converter.StringHttpMessageConverter@1d971ca]
11:32:01,235 DEBUG [org.springframework.web.servlet.DispatcherServlet] (http-/0.0.0.0:8080-1) Null ModelAndView returned to DispatcherServlet with name 'HelloWeb': assuming HandlerAdapter completed request handling
11:32:01,239 DEBUG [org.springframework.web.servlet.DispatcherServlet] (http-/0.0.0.0:8080-1) Successfully completed request
由于没有正在进行的事务,

延迟身份插入这是在将数据插入数据库时​​的行服务器打印。请帮我确定这个问题的解决方案。

2 个答案:

答案 0 :(得分:3)

如何使用交易

em.getTransaction().begin();
..
em..getTransaction().commit();

使用createEmployee()注释@Transactional方法,以启用弹出交易。

答案 1 :(得分:0)

1)您可以删除@Autowired注释     private CreateEmployeeDao createEmployeeDao 并手动注入它。