1

Spring Data と Hibernate を使用していますが、セット ID でエンティティを保存しようとするとエラーが発生します。

org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.snp.cm.persistency.contact.Contact; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.snp.cm.persistency.contact.Contact
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:668)

JpaRepositories を介してエンティティを更新する方法を教えてください。または、どの設定を見逃していますか?

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?> <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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="contactManagerPU">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>

    <class>com.snp.cm.persistency.contact.Contact</class>
    <class>com.snp.cm.persistency.contact.TelephoneNumber</class>

    <exclude-unlisted-classes>false</exclude-unlisted-classes>

    <properties>
        <property name="hibernate.max_fetch_depth" value="3" />
    </properties>
</persistence-unit>

春のコンテキスト:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
default-lazy-init="true">

<import resource="classpath*:META-INF/spring/dbs-repository-context.xml" />

<!-- Activates JPA's @PersistenceContext and @PersistenceUnit (if available) 
    annotations to be detected in bean classes. -->
<context:annotation-config />

<!-- Enable Transaction using @Transactional annotation -->
<tx:annotation-driven />

<bean id="daTM"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
    p:dataSource-ref="dataSource" />

<!-- Create local transaction manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
    p:entityManagerFactory-ref="entityManagerFactory" lazy-init="true"
    p:dataSource-ref="dataSource" />

<!-- Create EntityManagerFactory for injection into services. -->
<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource" p:persistenceXmlLocation-ref="persistenceXmlLocation">
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
        </bean>
    </property>
</bean>

<!-- Database access configuration -->
<bean id="persistenceXmlLocation" class="java.lang.String">
    <constructor-arg value="classpath*:META-INF/persistence.xml"></constructor-arg>
</bean>

<context:property-placeholder
    location="classpath:META-INF/spring/jdbc.properties" />

<!-- Dev's env DataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

別のプロジェクトで OpenJpa を使用しましたが、そのような問題はありませんでした。エンティティに ID が設定されている場合、「保存」メソッドは作成および更新を行いました。では、どうすればオブジェクトを更新できますか? 独自の更新方法を実装する必要がありますか?

失敗したテスト:

@Test
public void testRepositorySaveMethod() {
    Contact contact = new Contact();
    contact.setLastName("Carter");
    contact.setName("John");
    contact.setNickName(null);
    contact = this.contactRepository.save(contact);
    Assert.assertNotNull(contact.getContactId());

    TelephoneNumber telephoneNumber1 = new TelephoneNumber();
    telephoneNumber1.setTelephoneNumber("777 7777777");
    telephoneNumber1.setContact(contact);
    telephoneNumber1.setTelephoneType(TelephoneType.HOME);
    this.telephoneNumberRepository.save(telephoneNumber1);    // failes cause contact has already id

    contact = this.contactRepository.findOne(contact.getContactId());

    Assert.assertEquals(1, contact.getTelephoneNumbers().size());
}
4

2 に答える 2

4

その理由は次のとおりです。リポジトリ プロキシのsave(…)メソッドはトランザクションです。設定したJpaTransactionManagerように、Hibernate のライフサイクルはSessionトランザクションにバインドされます。これにより、テスト ケースSessionから呼び出しが返されたときに (およびトランザクション) が閉じられます。save(…)したがって、エンティティはSessionもう関連付けられていないため、後で表示される例外が発生します。

通常、テスト ケースでの解決策は、テスト メソッドを としてマークすること@Transactionalです。Spring テスト コンテキスト フレームワークを使用していると仮定すると、これにより、テスト メソッド全体に対してトランザクション (したがってSession) が開かれます (開かれたままになります)。

それを除けば、DataSourceTransactionManagerどこでも使用していないように見えるため、の宣言は時代遅れです。

于 2012-08-05T17:54:26.890 に答える
0

すべては次のように述べられています。detached entity passed to persist

おそらく、あなたは以下のようなことをしようとしています:

Entity detachedEntity = getDetachedEntitySomehow();
em.persist(detachedEntity); // it is causing error.

idを使用して更新しようとしているエンティティに対して設定されているようですpersist

この回答も見ることができます: JPA/EJB コードを使用した「永続化エラーに渡された切り離されたエンティティ」

于 2012-08-04T22:31:17.163 に答える