更新实体的Merge和saveOrUpdate抛出constraintViolationException

时间:2013-09-28 07:47:20

标签: java hibernate scala

I have an entity which contains a Map:

  @OneToMany(fetch = FetchType.EAGER)
  @JoinTable(name = "matrix_columns", joinColumns = Array(new JoinColumn(name = "id")))
  @MapKey(name="tenor")
  @Fetch(value = FetchMode.SELECT)
  @Access(AccessType.PROPERTY)
  def getInputMapNative: java.util.Map[Int,Column] = inputMap

Column包含一个数组

  @(OneToMany @field)(cascade = Array(CascadeType.ALL))
  @OrderColumn(name = "input_index")
  @Fetch(value = FetchMode.SELECT)
  var inputs:Array[Input] = _

因为我被Hibernate 3.6和这个bug Failed to lazily initialize a collection, no session or session was closed (despite eagerly fetching)所困扰,所以我尝试实现以下解决方法:

  • 我合并并保存列
  • 我更新地图并合并并保存父实体

(因为我不能依赖Hibernate级联)

但是,我仍然得到一个我不准备解决的例外

09:41:26.160 [GS-Notifier-pool-6-thread-2] ERROR o.h.util.JDBCExceptionReporter - Duplicate entry '781' for key 'inputs_id'
09:41:26.167 [GS-Notifier-pool-6-thread-2] ERROR o.h.e.d.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: could not insert collection: [Column.inputs#69]

这是我想用于在数据库中创建或保存新矩阵的代码

val mergedColumns = matrix.getInputMap.map {
                              case(tenor,column) =>
                                column.inputs foreach{
                                  item =>
                                    val mergedItem = session merge item
                                    session saveOrUpdate mergedItem
                                }
                                (tenor, (session merge column).asInstanceOf[Column])
                            }
  matrix.setInputMapNative(mergedColumns)
  val mergedMatrix = session merge matrix

  session saveOrUpdate mergedMatrix

  transaction.commit()

1 个答案:

答案 0 :(得分:0)

该例外与主键inputs_id的唯一性有关。 Hibernate尝试两次插入相同的条目,所以我想你的方法是合并并保存列并更新地图是这里的问题。

请考虑Session.saveOrUpdate。

要获得更好的答案,请提供其他信息,例如用于插入新条目的代码段。