New to Java - What's JPA and DAO?

mimipc picture mimipc · Mar 21, 2013 · Viewed 14.6k times · Source

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 :

  • Create class com.package.entity.User (generated from my database)
  • Create interface com.package.dao.UserDao
  • Create class com.package.dao.jpa.JpaUserDao implementing UserDao
  • Create EJB com.package.service.UserService with methods like 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 ?

Answer

Dave picture Dave · Mar 21, 2013

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:

  1. It is easier to read.
  2. It doesn't expose your database structure to the rest of the application
  3. It would be much easier for unit testing. The class that is getting users with green eyes only needs to create a "Mock" dao. This is easier than mocking JPA.

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.