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?