/** * 取得对象的主键值,辅助函数. * * @param entityClass 实体类型 * @param entity 实体对象 * @param <T> generic * @return 主键 * @throws NoSuchMethodException 找不到方法 * @throws IllegalAccessException 没有访问权限 * @throws InvocationTargetException 反射异常 */ public Serializable getId(Class entityClass, Object entity) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Assert.notNull(entity); String idName = getIdName(entityClass); String getterName = ReflectUtils.getGetterMethodName(entity, idName); return (Serializable) BeanUtils.invokeMethod(entity, getterName); }
/** * 取得对象的主键名,辅助函数. * * @param entityClass 实体类型 * @return 主键名称 */ public String getIdName(Class entityClass) { Assert.notNull(entityClass); entityClass = ReflectUtils.getOriginalClass(entityClass); ClassMetadata meta = this.getSessionFactory().getClassMetadata(entityClass); Assert.notNull(meta, "Class " + entityClass + " not define in hibernate session factory."); String idName = meta.getIdentifierPropertyName(); Assert.hasText(idName, entityClass.getSimpleName() + " has no identifier property define."); return idName; }
public void setId(Class entityClass, Object entity, Serializable idValue) { Assert.notNull(entity); Assert.notNull(idValue); try { String idName = getIdName(entityClass); String setterName = ReflectUtils.getSetterMethodName(idName); BeanUtils.invokeMethod(entity, setterName, idValue); } catch (NoSuchMethodException ex) { logger.info(ex.getMessage(), ex); } catch (IllegalAccessException ex) { logger.info(ex.getMessage(), ex); } catch (InvocationTargetException ex) { logger.info(ex.getMessage(), ex); } }