Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to design a DAO update method

Tags:

java

dao

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?

like image 725
faizal Avatar asked Nov 04 '14 16:11

faizal


2 Answers

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.

like image 106
cнŝdk Avatar answered Oct 09 '22 22:10

cнŝdk


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.

like image 29
Ezequiel Avatar answered Oct 10 '22 00:10

Ezequiel