Reputation: 86905
I want to update an entity in the database whenever the entity in my application contains data that is different from the DB entity.
My update method is as follows:
@Transactional
public void updateEntity(String a, String b, boolean c, Date d) { //some more params
MyEntity entity = dao.findEntityBy(a, b, c); //might be some more params
//nullcheck
if (!entity.getA().equals(a)) {
entity.setA(a);
}
if (!entity.getB().equals(b)) {
entity.setB(b);
}
//repeat per property... a-n
dao.save(entity);
}
Question: Should I check each attribute of the entity if it has changed and then only use the setter? Or should I just skip the checks and just override the entity?
MyEntity entity = dao.findEntityBy(a, b, c);
entity.setA(a);
entity.setB(b);
//...
dao.save(entity);
What is the perfered way? What are (dis)advantages of either solution?
Upvotes: 1
Views: 93
Reputation: 6190
In case you have many attributes, you can use the dynamic-update=true
to optimize the performance. The dynamic-update attribute tells Hibernate whether to include unmodified properties in the SQL UPDATE statement.
It can be configured as
@Entity
@Table(name = "MY_ENTITY")
@org.hibernate.annotations.Entity(
dynamicUpdate = true
)
public class MyEntity {
}
Upvotes: 3
Reputation: 11453
Pretty much in every "production ready" software you can see second version
MyEntity entity = dao.findEntityBy(a, b, c);
entity.setA(a);
entity.setB(b);
//...
dao.save(entity);
To be honest I don't see added value in first option (but added maintenance and lower readability can be seen).
Upvotes: 2