代码之家  ›  专栏  ›  技术社区  ›  alasdairg

如何确定Hibernate PostUpdateEventListener中的集合更改?

  •  4
  • alasdairg  · 技术社区  · 16 年前

    在Hibernate中,实现 允许您插入Hibernate的工作流,并使您有机会在保存实体时检查和比较实体属性的新旧值( 姿势更新事件 getOldState() getState() 目录 “旧值”和“新值”都是对集合的相同引用(因为集合本身没有更改,只是它的内容)。这意味着您只能看到该收藏的最新内容,即“新”内容。

    有人知道是否有办法确定某个实体拥有的集合的元素在工作流中此时是如何更改的吗?

    2 回复  |  直到 16 年前
        1
  •  7
  •   alasdairg    16 年前

    我想出了一个方法来做这件事,所以我会把它贴出来,以防它对其他人有用。这段代码循环遍历所有“旧状态”属性,对于任何持久集合,都会获取以前的内容“快照”。然后将其包装在一个不可修改的集合中,以便更好地度量:

    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
      }   
    
        2
  •  2
  •   zinking    10 年前

    似乎有一个专用于捕获集合更改的接口。

    Audit Log implementation Full

     public void onPreUpdateCollection(PreCollectionUpdateEvent event) {
        if (bypass(event.getAffectedOwnerOrNull().getClass())) {
            return;
        }
        CollectionEntry collectionEntry = getCollectionEntry(event);    
     }
    
    
     protected CollectionEntry getCollectionEntry(AbstractCollectionEvent event) {
         return event.getSession().getPersistenceContext()
                .getCollectionEntry(event.getCollection());
     }