How do you design a DAO class for an entity that has multiple fields?
For example for the below entity :
public class MyEntity{
private long id;
private int field1;
private String field2;
private Date field3;
private Date field4;
private int field5;
}
Should i create a DAO class that has update methods for each field like :
public class MyEntityDao{
public insert(MyEntity myEntity);
public delete(MyEntity myEntity);
public get(long id);
public updateField1(MyEntity myEntity)
public updateField2(MyEntity myEntity)
public updateField3(MyEntity myEntity)
public updateField4(MyEntity myEntity)
public updateField5(MyEntity myEntity)
}
It seems like the logical thing to do but i usually see example of just a single update()
method. In that case, how should the DAO determine which field is to be updated in the database? Does it just update all fields blindly, even though only 1 might have changed? Or should the entity class have flags as members to indicate which fields have changed?
You just need to pass the entity to update and the DAO will automatically determine the changed fields and update them in the DB.
public update(MyEntity myEntity);
And then the DAO gets the id of myEntity and update the entity in the database.
You should update all fields at once.
why?: It most wasteful to query for the object, then compare with the actual entity, determine which fields must be updated, create a different PreparedStatment for each combination. And finally update those fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With