在Spring MVC 3.0.5控制器中,JPA实体未持久化到数据库
在下面的代码中,persist()不返回异常,但实体未存储在数据库中在Spring MVC 3.0.5控制器中,JPA实体未持久化到数据库,spring,jpa,Spring,Jpa,在下面的代码中,persist()不返回异常,但实体未存储在数据库中 @RequestMapping(method = RequestMethod.POST) public String form() { EntityManager em = this.emf.createEntityManager(); TaxRates t = new TaxRates(); t.setCountry("US"); // set more pro
@RequestMapping(method = RequestMethod.POST)
public String form() {
EntityManager em = this.emf.createEntityManager();
TaxRates t = new TaxRates();
t.setCountry("US");
// set more properties
em.persist(t);
em.close();
...
}
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">
<persistence-unit name="TT-SpringMVCPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
...
<class>com.sajee.db.TaxRates</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:jtds:sqlserver://localhost:1234/mydb"/>
<property name="javax.persistence.jdbc.password" value="Password1"/>
<property name="javax.persistence.jdbc.driver" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
</properties>
</persistence-unit>
</persistence>
org.eclipse.persistence.jpa.PersistenceProvider
...
com.sajee.db.TaxRates
真的
我不需要任何事务支持或任何花哨的企业功能支持。我只想创建一个实体并将其保存到数据库中
@RequestMapping(method = RequestMethod.POST)
public String form() {
EntityManager em = this.emf.createEntityManager();
TaxRates t = new TaxRates();
t.setCountry("US");
// set more properties
em.persist(t);
em.close();
...
}
我哪里做错了 persist()
不会立即将对象写入数据库。相反,它将对象标记为持久对象,以便在事务提交之前(或在执行查询之前,或在显式flush()
操作期间)将其写入数据库
因此,即使您不需要事务行为,也必须管理事务。您可以按如下方式手动执行此操作:
@RequestMapping(method = RequestMethod.POST)
public String form() {
EntityManager em = this.emf.createEntityManager();
TaxRates t = new TaxRates();
t.setCountry("US");
// set more properties
em.getTransaction().begin();
em.persist(t);
em.getTransaction().commit();
em.close();
...
}
但这是一种更方便的方法