Java 无法在JPA+;中持久化实体;春天,没有错误

Java 无法在JPA+;中持久化实体;春天,没有错误,java,mysql,spring,hibernate,jpa,Java,Mysql,Spring,Hibernate,Jpa,我试图将实体持久化到JAP+Spring中,但它并没有将数据插入数据库,并没有显示任何错误。当我在服务器上部署我的项目时,我的表是在DB中自动创建的,当我手动将数据插入DB并尝试获取数据时,它成功地从DB中获取数据,但在插入数据时,它不会给出任何错误,也不会将数据插入DB。下面是我的代码,请帮忙。 web.xml <display-name>Spring MVC Application</display-name> <servlet> &l

我试图将实体持久化到JAP+Spring中,但它并没有将数据插入数据库,并没有显示任何错误。当我在服务器上部署我的项目时,我的表是在DB中自动创建的,当我手动将数据插入DB并尝试获取数据时,它成功地从DB中获取数据,但在插入数据时,它不会给出任何错误,也不会将数据插入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>
<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>
<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>
<?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>
CreateEmployeeDao.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);
    }
}
@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();
    }
}
@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;
    }
}
Employee.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);
    }
}
@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();
    }
}
@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

由于没有正在进行的事务而延迟身份插入这是将数据插入数据库时的行服务器打印。请帮助我确定此问题的解决方案。

使用事务如何

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

用启用spring事务的
@Transactional
注释
createEmployee()
方法。

1)您可以在 私有CreateEmployeeDao CreateEmployeeDao
然后手动注入。

第一个问题:您可以从工作台或命令行直接将
插入到数据库中吗?您的数据库可访问吗?我插入db vai命令行,然后它正确插入,我的get请求也获取我使用命令行插入的数据。您是否显示了实际代码?例如,您是否有类似于
接口CreateEmployeeDao{}
类CreateEmployeeDaoImpl实现CreateEmployeeDao{}
?Nan…没有接口…这是我的演示项目的实际代码,它说不起作用“不允许在共享EntityManager上创建事务-改用Spring事务或EJB CMT”在这种情况下,请使用@Transactional(启用Spring事务的@Transactional)注释createEmployee()方法。请删除
@Transactional(value=“transactionManager”,propagation=propagation.REQUIRED)
来自CreateEmployeeDao,如回答中所述,仅在createEmployee()方法上使用@Transactional。