use*_*465 6 java apache-commons apache-commons-beanutils spring-framework-beans
试图在这里做一些简单的事情。获取一个 Entity 对象并将其同名属性复制到另一个 bean。
你可以用 Apache commons 做到这一点
org.apache.commons.beanutils.BeanUtils.copyProperties(source,target)
Run Code Online (Sandbox Code Playgroud)
但这里的问题是我们可能有一些特定于实体 bean 的属性(元数据,如 created、lastUpdated 等时间戳),我们不想复制到目标 bean 并且 Apache Commons BeanUtils 不支持忽略属性. 我被推向了 Spring BeanUtils 的方向
org.springframework.beans.BeanUtils.copyProperties(source,target,ignoreProperties)
Run Code Online (Sandbox Code Playgroud)
其中 ignoreProperties 是您要忽略的属性名称的字符串数组。现在的问题似乎是在执行此属性复制时,它会将源对象的属性设为 null!由于源对象是一个实体对象,当事务被提交时,我们会得到一个带有强制 id 字段的 HibernateException
org.hibernate.HibernateException: identifier of an instance {source} was altered from {originalId} to null
Run Code Online (Sandbox Code Playgroud)
任何人都知道解决这个问题的方法,或者您是否致力于使用其中一种?让我困惑的是为什么公地库不支持在复制时忽略属性,或者为什么 springframework BeanUtils 似乎执行剪切/粘贴而不是复制/粘贴。