I'm new to Java and i'm trying to make a web project with servlets. I'd like to query my database but I think I don't understand everything about JPA and DAO.
I've been taught to do things this way :
public List<User> findAll()
I've heard there's no need to create a DAO interface with JPA but I'm completely lost and I don't understand at all what I should do or what an EJB is. I simply want to find all the users in my database and display their names following Java's good practices.
It's allready OK for my servlets and JSPs.
What would you recommend ?
DAO stands for "Data Access Object". It abstracts the concept of "getting something from a datastore". Your DAO objects can be implemented with JDBC calls, JPA calls or whatever. Maybe it calls some remote webservice. Having a DAO over JPA seems redundant and it does add a layer, but I think it is worth it.
For example, you might have a use case of "display users that have green eyes".
with straight JPA:
List<User> users = entityManager.createQuery("select u from User u where u.EyeColor = 'green'"");
with a DAO you'd have:
List<User> users = dao.UsersWithEyeColor("green");
The DAO here has a couple of advantages:
These are just a few arguments for using a DAO. For a very simple, small application it might be too much overhead. But for anything that will become larger and need to be maintained for many years I think it is worth it.