我想出了一个方法来做这件事,所以我会把它贴出来,以防它对其他人有用。这段代码循环遍历所有“旧状态”属性,对于任何持久集合,都会获取以前的内容“快照”。然后将其包装在一个不可修改的集合中,以便更好地度量:
public void onPostUpdate( PostUpdateEvent event )
{
for ( Object item: event.getOldState() )
{
Object previousContents = null;
if ( item != null && item instanceof PersistentCollection )
{
PersistentCollection pc = (PersistentCollection) item;
PersistenceContext context = session.getPersistenceContext();
CollectionEntry entry = context.getCollectionEntry( pc );
Object snapshot = entry.getSnapshot();
if ( snapshot == null )
continue;
if ( pc instanceof List )
{
previousContents = Collections.unmodifiableList( (List) snapshot );
}
else if ( pc instanceof Map )
{
previousContents = Collections.unmodifiableMap( (Map) snapshot );
}
else if ( pc instanceof Set )
{
//Set snapshot is actually stored as a Map
Map snapshotMap = (Map) snapshot;
previousContents = Collections.unmodifiableSet( new HashSet( snapshotMap.values() ) );
}
else
previousContents = pc;
//Do something with previousContents here
}