Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What methods should be contained in the DAO? [closed]

Tags:

java

dao

The question is about the pattern understanding itself, not about a specific implementation.

I've read about the DAO pattern and the question that arised was what methods should be neccessary included in the DAO? For instance,

public interface UserDAO{

    public User getUserById(Integer id);

    public void deleteUser(Integer id);

    public void updateUser(Integer id, User user);

    public void createUser(User user);
}

Can we say that the interface satisfies the DAO-pattern? If not, what methods should I add/remove from it?

like image 686
user3663882 Avatar asked Dec 19 '25 20:12

user3663882


2 Answers

If we are talking into more generic methods, than you could go with:

public interface GenericDao<D>{

    public D get(Long id);// as Id use Long instead of Integer, Ids can be very large numbers, Int can be not enough

    public Collection<D> getList(SearchCriteria crit); //for retrieving more than one element 

    public void remove(Long id);

    public void update(D entity); // remember that updated record should have already id inside, you can add assert inside

    public void create(D entity); // assert that id is null
}

The last step can be replacing update/add with save method (optional).

You can use generics, and make D implement some interface that has getId() method, this will help to write one class for all DAO, as parent, will reduce your code:)

public interface Model implement Serializable{

   Long getId();

}

And inside of youd DAO, you would write this:

public interface UserDAO <D extends Model>{
...

From this point you can inside of your GenericDaoImpl implement all crud operations. And all your dao, like UserDao will simply extend GenericDaoImpl, and Dao interfaces like UserDao will extend GenericDao interface.

So you will hide common logic inside Generic classes, and add specific methods only to some Dao, like fetching users by email, username or age:) Your code will be cleaner and more readable.

like image 179
Beri Avatar answered Dec 22 '25 11:12

Beri


Basically DAO layer Contains function related to CRUD(Create, Read, Update, Delete) operations. As your interface mostly contains these functions only, so your interface is acceptable. If you want generic then the other answer is also good. Also You can add more CRUD function according to your need like :

getUserByEmail(String email){}

You can add these type of functions also..

like image 32
BigBang Avatar answered Dec 22 '25 10:12

BigBang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!