当给定的id已存在时,Spring Data JPA save方法不会更新数据库实体

时间:2015-10-16 10:04:11

标签: java spring hibernate jpa

由于某种原因,我的JPA存储库不会更新现有数据库实体,但即使参数对象具有已存在于数据库中的id,也会创建一个新实体。

这是我的配置:

<jpa:repositories base-package="com.someName.repository.support"
                  transaction-manager-ref="transactionManager_Support"
                  entity-manager-factory-ref="entityManagerFactory_Support"/>

<bean id="transactionManager_Support" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory_Support"/>
    <property name="nestedTransactionAllowed" value="true"/>
</bean>

<bean id="entityManagerFactory_Support" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSourceSupport"/>
    <property name="persistenceXmlLocation" value="classpath:persistence.xml"/>
    <property name="persistenceUnitName" value="persistenceUnit_SUPPORT"/>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.enable_lazy_load_no_trans">true</prop>
        </props>
    </property>
</bean>

<persistence-unit name="persistenceUnit_SUPPORT" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
 <!-- List of all entity classes here -->
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" />
        <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" />
        <property name="hibernate.connection.charSet" value="UTF-8" />    
    </properties>
</persistence-unit>

我在服务中有一个包装方法,如下所示:

@Transactional("transactionManager_Support")
public TestingResult save(TestingResult testingResult) {

    try {
        testingResult = testingResultRepository.saveAndFlush(testingResult);
        LOGGER.info(String.format("Testing Result with id [%d] was successfully persisted", testingResult.getId()));
    } catch (Exception e) {
        LOGGER.error("Error persisting Testing Result");
    }

    return testingResult;
}

多次调用此方法。第一次testingResult具有null id,因此它以预期的新id保存。之后,再次保存具有一些新属性集的相同对象,因为我需要更新DB中的现有实体。但是,创建DB中的新记录时,id增加1。 任何人都可以澄清为什么会发生这种行为?

0 个答案:

没有答案