2010-11-20 9 views
1

persist()は例外を除いて例外を返しますが、エンティティはデータベースに格納されません。Spring MVC 3.0.5コントローラでJPAエンティティがデータベースに永続化されない

@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> 

私は、任意のトランザクションサポートまたは任意の空想のエンタープライズ機能のサポートを必要としません。エンティティを作成してデータベースに保存するだけです。

どこが間違っていますか?

答えて

2

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(); 
     ... 
} 

しかしはそれを行うために、より便利な方法です:次のように手動でそれを行うことができます。

関連する問題