【问题标题】:Inserting value in DB or update existing one在数据库中插入值或更新现有值
【发布时间】:2013-02-04 02:03:09
【问题描述】:

我正在尝试使用 EclipseLink 管理我的数据库,但遇到了一个严重的问题。

这是我的简单方法

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

如您所见,这真的很容易。 如果数据库包含实体,我将合并更改以将它们存储在数据库中,否则我只是创建一个新实体。

但它不会起作用,因为它会抛出关于重复主 ket 的异常,即使包含返回 true!

这有什么问题?

【问题讨论】:

  • 对象 eventto 来自哪里?它是来自 EntityManager 还是在存在上下文之外创建的?
  • 它是在PersitenceContext之外创建的,为什么?

标签: java mysql jpa ejb eclipselink


【解决方案1】:

如果实体被放入 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;

【讨论】:

    猜你喜欢
    • 2019-06-14
    • 2013-08-06
    • 2016-01-14
    • 1970-01-01
    • 2016-06-21
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多