Caused by: org.hibernate.HibernateException: Found shared references to a collection: com.*****.parameterize.entity.UiueMenuConfig.uiueAssociateMenuConfig
at org.hibernate.engine.internal.Collections.processReachableCollection(Collections.java:180)
at org.hibernate.event.internal.FlushVisitor.processCollection(FlushVisitor.java:59)
at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:121)
at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:82)
at org.hibernate.event.internal.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:76)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:172)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:231)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:102)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:55)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:584)
原因分析:BeanUtil.copyProperties() 的方式复制一个实体bean的时候,这个实体bean有一个集合属性,因为这个方法只是做了一个浅拷贝,所以新拷贝的实体跟旧的实体引用了同一个集合,而这在hibernate中是不允许的,所以报错。
解决:设置集合为Null,忽略集合类型属性,创建新的集合,添加旧的集合数据
/** * 注意此方法忽略集合类型参数 * @param source * @return */ public static String[] getNullOrCollectPropertyNames (Object source) { final BeanWrapper src = new BeanWrapperImpl(source); java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors(); Set<String> emptyNames = new HashSet<String>(); for(java.beans.PropertyDescriptor pd : pds) { Object srcValue = src.getPropertyValue(pd.getName()); if (srcValue == null) {emptyNames.add(pd.getName()); }else if (srcValue instanceof Collection){ emptyNames.add(pd.getName()); } } String[] result = new String[emptyNames.size()]; return emptyNames.toArray(result); } /** * 注意此方法忽略集合类型参数 * @param src * @param target */ public static void copyProperties(Object src, Object target) { BeanUtils.copyProperties(src, target, getNullOrCollectPropertyNames(src)); }