在休眠中的 onPostUpdateCollection 事件中获取集合中的旧值

Che*_*iya 2 java hibernate

我使用 hibernate 4.2 进行持久存储。我正在实现休眠事件侦听器,以便在修改特定对象时获取通知。尝试PostUpdateEventListener在休眠中实现事件,但在更新集合值时不会触发方法。目前正在实现PostCollectionUpdateEventListener集合更新时触发的方法。

班级如下

public class Employee {
  private int id;
  private String name;
  private Set<Address> addresses;

  //all getters and setters are implemented.
}

public class Address {
  private int id;
  private String street;
  private String city;

  //all getters and setters are implemented.
}
Run Code Online (Sandbox Code Playgroud)

我已将映射实现为 xml 文件,其中包含所有映射和以下设置映射

在 Employee.hbm.xml 中

<hibernate-mapping>
  <class name="Employee">
  ... all mappings
  <set name="addresses" inverse="true" cascade="all-delete-orphan">
    <key column="Emp_id"/>
    <one-to-many class="Address"/>
  </set>
</hibernate-mapping>
Run Code Online (Sandbox Code Playgroud)

地址 .hbm.xml 文件已正确实现。

在休眠事件监听器中

public void onPostUpdateCollection(PostCollectionUpdateEvent event) {
  Object obj = event.getAffectedOwnerOrNull();
  //this gives me updated values.

  I want now code to get old collection values which going to be deleted.
}
Run Code Online (Sandbox Code Playgroud)

我尝试过以下行

PersistentCollection collection = event.getCollection();
// this gives new update collection values of addresses
Run Code Online (Sandbox Code Playgroud)

我在 PersistentCollection 中看到了方法Serializable getStoredSnapshot(),但它给出了空值。

无论如何,如果我可以获得旧的收藏价值,请帮助我。我正在插入新的地址值,以便它触发onPostUpdateCollection()Employee 类对象上的事件方法。

我的问题是:如何检索集合的旧值?尝试获取几天内的旧值,我们将非常感谢任何帮助。提前致谢。

Che*_*iya 5

在 PostCollectionUpdateEventListener 中,无法获取旧的集合值。我使用 PreCollectionUpdateEventListener 类来获取旧的集合值,如下所示

public void onPreUpdateCollection(PreCollectionUpdateEvent event) {
  PersistentCollection collection = event.getCollection();
  HashMap snapshot = (HashMap) collection.getStoredSnapshot();
  //set values are also stored as map values with same key and value as set value
  Set<Map.Entry> set = snapshot.entrySet();
  //Now this set contains key value of old collection values before update
}
Run Code Online (Sandbox Code Playgroud)