Hibernate SaveOrUpdate错误/合并时出现不同的错误

时间:2011-10-26 18:42:24

标签: hibernate merge save

Hibernate Object:

提供商 - >它与ProviderAddress有一对多的关系 和ProviderStatusDetail的一对多关系

之前我们将Provider Object保存/更新到数据库。一切都很好。现在我们必须将旧值保存到History表,然后保存/更新Provider表。

守则的部分内容:

public void saveProvider(Provider provider) {

    //Get Existing Data from Provider
    Provider existingProvider = (Provider) this.getHibernateTemplate().get(Provider.class, provider.getProviderId());

    ProviderHistory providerHistory = null;
    providerHistory = new ProviderHistory();

    providerHistory.setProviderId(existingProvider.getProviderId());
    ...

    //Get Existing Data from Provider Status Detail
    ProviderStatusDetail existingProviderStatusDetail = (ProviderStatusDetail) this.getHibernateTemplate().get(ProviderStatusDetail.class,              

        existingProvider.getProviderStatusDetails().get(0).getProviderStatusDetailId());

    providerHistory.setTypeCode(existingProviderStatusDetail.getTypeCode());
    ...

    // Save Provider History Table
    this.getHibernateTemplate().save(providerHistory);

    // Get Existing Address Details
    Address address1 = this.getHibernateTemplate().get(Address.class,
                            existingProvider.getAddresses().get(0).getAddressId());

    // Save exsiting Practice Address to Address History Table
    ProviderAddressHistory practiceAdrHistory = null;
    adrHistory = new ProviderAddressHistory();

    adrHistory.setProviderId(provider.getProviderId());
    ...

    this.getHibernateTemplate().save(practiceAdrHistory);

    //Make some changes to the Status Detail Object
    for (ProviderStatusDetail psd : provider.getProviderStatusDetails()) {

            //Provider Type check
            if (psd.getTypeCode() != null 
                    && psd.getTypeCode() == 0) {
                psd.setTypeCode(null);
            }
    ...
    } 

    //Make sonme changes to Provider Object
    if (provider != null) {
            if (provider.getName() != null) {
                if (provider.getName().getPrefix() == 0) {
                    provider.getName().setPrefix(null);
                }
    }


    //Save Provider
    //this.getHibernateTemplate().saveOrUpdate(provider); //Error 1 - So commented this line

    //Save Provider with merge
    if (provider.getProviderId() > 0) {
            this.getHibernateTemplate().merge(provider); //Error 2
    } else {
            this.getHibernateTemplate().saveOrUpdate(provider);
    }
} 

错误1: 此行在历史记录表更改之前用于正常工作。现在我收到了这个错误:

A different object with the same identifier value was already associated with the session. 

错误2:

Caused by: org.hibernate.TransientObjectException: object is an unsaved transient instance - save the transient instance before merging: com.abcd.ProviderStatusDetail

有人可以帮我解决这个问题。希望我的问题很明确。非常感谢。

1 个答案:

答案 0 :(得分:0)

使用以下方法解决了问题:

session.flush()
session.clear()

在最后一次saveOrUpdate()之前。删除了merge()。