---
title: "Hibernate ClassMetadata and Javabean PropertyDescriptor"
author: "maflyp"
date: "2012-03-08T11:09:12Z"
tags: []
categories: ["编程语言"]
slug: "hibernate-classmetadata-and-javabean-propertydescriptor"
draft: false
lastmod: "2012-03-08T11:09:12Z"
id: 1445646
url: "https://maflyp.iteye.com/blog/1445646"
---

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);