0

I am performing the bulk upload from excel file. I want to create insert for new products and update the existing one, with stockId being the unique key which is present on file, primary key is stoneId and is not present on file. Insertion is working as expected but I am facing difficulties with updates. As I know we cannot directly merge a transient object in hibernate I want to know the best way to achieve this.

I have tried below options so far: 1) Using apache commons BeanUtils:

    Stone s = getStoneByStockNo(t.getStockNo());
    Integer id = s.getStoneId();
    try {
        BeanUtils.copyProperties(s, t);
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    s.setStoneId(id);
    entityManager.merge(s);

This gives me Duplicate entry 'xxxxxxxxx' for key (stockNo)

2) I have tried Spring BeanUtils:

    Stone s = getStoneByStockNo(t.getStockNo());
    String [] ignore = {"stoneId"};
    BeanUtils.copyProperties(s, t, ignore);
    entityManager.merge(s);

This donot gives me any error but due to some reason BeanUtils is not copying the properties and I am not getting any updated values.

3) I tried to manually set the values using setter:

    Stone s = getStoneByStockNo(t.getStockNo());
    s.setSize(t.getSize());
    s.setPurity(t.getPurity());
    s.setLab(t.getLab());
    entityManager.merge(s);

This is working as expected but I donot like this way as I have large number of properties and will have to modify the code every time when their is any change in properties

May be I am missing something over here. Could anyone suggest a better way to achieve this?

Harsh
  • 445
  • 1
  • 5
  • 13

1 Answers1

0

In your second approach you are trying to merge your source entity insted of target. As you can see in doc, It is opposite of apache commons BeanUtils.

Try this way and it will copy all values from t to s and will ignore values you have passed in array.

Stone s = getStoneByStockNo(t.getStockNo());
String [] ignore = {"stoneId"};
BeanUtils.copyProperties(t, s, ignore);
entityManager.merge(s);
Mihir Chauhan
  • 141
  • 1
  • 11
  • For anyone else facing similar problem this question was very helpful to me: https://stackoverflow.com/questions/29297468/copy-properties-from-one-bean-to-another-not-the-same-class-recursively-inclu – Harsh Dec 19 '17 at 07:27