Total Pageviews

2011/08/23

had objects of type "gov.fdc.nig.domain.Nigt038PK" but expected signature "gov.fdc.nig.domain.Nigu038PK"

Problem
As I utilize Appche commons PropertyUtils.copyProperties API, it show this error message in runtime

Cannot invoke gov.fdc.nig.domain.Nigu038.setId on bean class 'class gov.fdc.nig.domain.Nigu038' - had objects of type "gov.fdc.nig.domain.Nigt038PK" but expected signature "gov.fdc.nig.domain.Nigu038PK"


Root Cause
Here is Nigt038's attributes
1:  @Entity   
2:  @EntityListeners({EntityListener.class})   
3:  @Table(name = "NIGT038")   
4:  public class Nigt038 extends DomainBase {   
5:       // Fields   
6:       private Nigt038PK id;   
7:       private String vioFactNm;   
8:       private Timestamp timeStamp;   
9:       private String updateCd;   
10:       private String userId;   
11:       private String updateDate;   
12:       //..........   



Here is Nigu038's attributes
1:  @Entity   
2:  @EntityListeners({EntityListener.class})   
3:  @Table(name = "NIGU038")   
4:  public class Nigu038 extends DomainBase {   
5:       // Fields   
6:       private Nigu038PK id;   
7:       private String vioFactNm;   
8:       private Timestamp timeStamp;   
9:       private String userId;   
10:       private String updateDate;   
11:       //........   

The two class the same attrbute name, but have different type. It's the reason why it fails to do object copy.
And in our case, we don't need to copy id attributes.

Solution
We need to igore the "id" attribute, so we use this way to do property copy.


1:    /**  
2:     * Copy properties.  
3:     *  
4:     * @param dest  
5:     *      the dest  
6:     * @param source  
7:     *      the source  
8:     */  
9:    public void copyProperties(Object dest, Object source) {  
10:      try {  
11:        PropertyDescriptor[] destDesc = PropertyUtils.getPropertyDescriptors(dest);  
12:        for (int i = 0; i < destDesc.length; i++) {  
13:          Class<?> destType = destDesc[i].getPropertyType();  
14:          Class<?> origType = PropertyUtils.getPropertyType(source, destDesc[i].getName());  
15:          if ((destType != null && destType.equals(origType) && !destType.equals(Class.class) && !"id"  
16:            .equals(destDesc[i].getName()))) {  
17:            Object value = PropertyUtils.getProperty(source, destDesc[i].getName());  
18:            PropertyUtils.setProperty(dest, destDesc[i].getName(), value);  
19:          }  
20:        }  
21:      } catch (IllegalAccessException e) {  
22:        e.printStackTrace();  
23:      } catch (InvocationTargetException e) {  
24:        e.printStackTrace();  
25:      } catch (NoSuchMethodException e) {  
26:        e.printStackTrace();  
27:      }  
28:    }  

No comments: