0

EclipseLinkを使用してDBを管理しようとしていますが、深刻な問題が発生しています。

これが私の簡単な方法です

    PUEntityManager.getTransaction().begin();
    if (!PUEntityManager.contains(evento)) {
        PUEntityManager.persist(evento);            
    } else {
        PUEntityManager.merge(evento);
        //PUEntityManager.refresh(evento);
    }
    PUEntityManager.getTransaction().commit();

ご覧のとおり、とても簡単です。DBにエンティティが含まれている場合は、変更をマージしてDBに保存します。それ以外の場合は、新しいエンティティを作成します。

ただし、containsがtrueを返したとしても、重複するプライマリketに関する例外がスローされるため、機能しません。

どうしたの?

4

1 に答える 1

0

エンティティがEclipselinkの外部のデータベースに配置されている場合は、変更を永続化する前に、エンティティのロードを試行する必要があります。これは、一貫性を確保するための唯一の信頼できる方法です。

Object primaryKey = evento.getPrimaryKey();
Object tmpEvento = PUEntityManager.load( Evento.class, primaryKey )

if ( tmpEvento == null )
{
    tmpEvento = PUEntityManager.persist( evento );
}
else
{
    // If the evento already exists, you need to decide which attributes of
    // the evento in the DB that you want to copy over to the evento
    // you want to merge.  This is only an example.
    tmpEvento.setXXX( evento.getXXX() );
    tmpEvento.setYYY( evento.getYYY() );
    tmpEvento = PUEntityManager.merge( tmpEvento );
}

// I recommend returning the tmpEvento object after persisting or merging.
return tmpEvento;
于 2013-02-19T13:40:02.863 に答える