6

Trying to do something simple here. Take an Entity object and copy it's identically named properties to another bean.

You can do this with Apache commons

org.apache.commons.beanutils.BeanUtils.copyProperties(source,target)

but the issue here is that we may have some properties that are specific to the entity bean (metadata like created,lastUpdated, etc timestamps) that we don't want to copy to the target bean and Apache Commons BeanUtils does not support ignoring of properties. I was pushed in the direction of Spring BeanUtils

org.springframework.beans.BeanUtils.copyProperties(source,target,ignoreProperties)

Where ignoreProperties is an array of strings of the property name syou want to ignore. Now the issue seems to be when performing this property copy it nulls the properties of the source object! As the source object is an Entity object with a mandatory id field when the transaction is committed we get a HibernateException

org.hibernate.HibernateException: identifier of an instance {source} was altered from {originalId} to null

Anyone know a way around this or are you committed to using one or the other? Confusing to me why the commons librariy doesn't support ignoring properties while copying or why the springframework BeanUtils seems to perform a cut/paste instead of a copy/paste.

user898465
  • 944
  • 1
  • 12
  • 23
  • 1
    According to [Spring source code](https://github.com/spring-projects/spring-framework/blob/master/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java#L670), what you are saying is not the case: ignored properties are, indeed, ignored. You need to search for the problem elsewhere. – M. Prokhorov Apr 11 '18 at 13:25
  • I didn't say that they were, read the question again. What I said happens is that source Object's property fields are cut and pasted rather than copy and pasted, which means the fields in the source object are set to null, which when it's an entity object causes issues when the transaction is committed. – user898465 Apr 11 '18 at 13:39
  • 2
    It is, again, not the problem of Spring implementation. It can only happen if your code nulls out the property when a getter is invoked. – M. Prokhorov Apr 11 '18 at 13:44
  • 2
    Just realised the issue here, Apache uses (target, source), Springframework uses (source, target), doh. – user898465 Apr 11 '18 at 14:10
  • great answer. simple difference. – Lova Chittumuri Jul 03 '18 at 11:29
  • 1
    Also, when using Spring BeanUtils you dont need to do an explicit try/catch or handle throws which you have to do when you are using BeanUtils from Apache package so +1 to Spring BeanUtils – Neeraj Apr 23 '19 at 16:26

0 Answers0