简体   繁体   中英

Not able to Persist entity in JPA + Spring, No error

I am trying to persist entity into JAP+Spring but it is not inserting data into DB, No error is displayed. when I deploy my project on server my table is created automatically in DB and when I insert data manually into DB and try to fetch it, it successfully fetch the data from DB, but while inserting data it doesn't it doesn't give any error nor it insert it in DB. below is my code please help. 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;
    }
}

below is my server log when i hit request for inserting data

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

delaying identity-insert due to no transaction in progress this is the line server print while inserting data into DB. Please help me identifying the solution of this problem.

how about using transactions

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

or

annotate the createEmployee() method with @Transactional which enables spring transactions.

1)您可以删除私有CreateEmployeeDao createEmployeeDao上的@Autowired注释并手动注入它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM