java - 无法在 JPA + Spring 中保留实体,没有错误

标签 java mysql spring hibernate jpa

我正在尝试将实体持久化到 JAP+Spring 中,但它没有将数据插入到数据库中,没有显示任何错误。当我在服务器上部署我的项目时,我的表是在数据库中自动创建的,当我手动将数据插入数据库并尝试获取它时,它成功地从数据库中获取数据,但是在插入数据时它没有提供任何信息错误,也不会将其插入数据库。下面是我的代码请帮助。 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();
    }
}

员工.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

delaying identity-insert due to no transaction in progress 这是将数据插入数据库时​​的行服务器打印。请帮我确定这个问题的解决方案。

最佳答案

如何使用交易

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

使用 @Transactional 注释 createEmployee() 方法,它启用 spring 事务。

关于java - 无法在 JPA + Spring 中保留实体,没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34149142/

相关文章:

java - spring-boot-starter-data-jpa 依赖错误

c# - 将带有 "params"修饰符的 C# 方法转换为 Java

java - System.out.println() 从数据库到表

MySQL集群传播

php - 在 PHP 字符串中格式化 MySQL 代码

mysql - 只有 2 个外键的表有什么作用?

spring - @Qualifier 中的 SpEL 引用同一个 bean

java - 我看不到框架内的组件

java - 无法使用 FileObserver 观察文件夹内的文件

java - Spring WebFlux - 处理 404 的单一方法?