ITeye博客

Hibernate ClassMetadata and Javabean PropertyDescriptor

maflyp · 2012-03-08 11:09 · 编程语言 · Markdown

1. Hibernate ClassMetadata Provided by hibernate, can be used to copy beans and so on, however, need hibernate session. SessionFactory sf = session.getSessionFactory(); ClassMetadata sourceMetadata = sf.getClassMetadata(sourceEntity.getClass()); ClassMetadata targetMetadata = sf.getClassMetadata(targetEntity.getClass()); Type sourcePropertyType = null; Type tragePropertyType = null; CollectionMetadata collectionMetadata = null; // copy primary key and set primary key. Serializable sourcePk = sourceMetadata.getIdentifier(sourceEntity, EntityMode.POJO); Serializable targetPk = targetMetadata.getIdentifier(targetEntity, EntityMode.POJO); if (targetPk == null) { targetMetadata.setIdentifier(targetEntity, sourcePk, EntityMode.POJO); } // copy other properties. for (String property : sourceMetadata.getPropertyNames()) { sourcePropertyType = sourceMetadata.getPropertyType(property); tragePropertyType = targetMetadata.getPropertyType(property); if (sourcePropertyType == null || tragePropertyType == null) { continue; } // copy primary key; if (sourcePropertyType.isCollectionType() && tragePropertyType.isCollectionType()) { Collection sourceValues = (Collection) sourceMetadata.getPropertyValue(sourceEntity, property, EntityMode.POJO); Collection targetValues = (Collection) targetMetadata.getPropertyValue(targetEntity, property, EntityMode.POJO); collectionMetadata = sf.getCollectionMetadata(sourceMetadata.getEntityName() + "." + property); Class sourceClazz = collectionMetadata.getElementType().getReturnedClass(); collectionMetadata = sf.getCollectionMetadata(targetMetadata.getEntityName() + "." + property); Class targetClazz = collectionMetadata.getElementType().getReturnedClass(); if (sourceValues != targetValues) { copyCollection(sourceClazz, sourceValues, targetClazz, targetValues, session, targetEntity); } } else { targetMetadata.setPropertyValue(targetEntity, property, sourceMetadata.getPropertyValue(sourceEntity, property, EntityMode.POJO), EntityMode.POJO); } } 2. Javabean PropertyDescriptor Provided by jdk reflection, can be used to copy beans and so on. PropertyDescriptor[] properties = Introspector.getBeanInfo(masterTo.getClass()).getPropertyDescriptors(); //通过PropertyDescriptor ps进行设值和取值。 pd.getWriteMethod().invoke(clazzIns, Long.valueOf(keys[i])); Object o = pd.getReadMethod().invoke(domain);

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。