Home > java > Using DAO with ORM

Using DAO with ORM

I’m using iBatis in the application I’m currently working on. And since we try to create a well designed code, we are using the DAO design pattern to call the iBatis’s api.

Recently I started using JPA and so I’ve quiclky start creating DAO to put my JPA code in it.

My service layer calls my DAOs and that’s great, but …

When you use JPA or any ORM tools there is many things that will be done out of the scope of your code.

Lets take the OneToMany association for example and say that you have set a transitive persistence.

@Entity
@Table(name="USER")
public class User implements Serializable {
private static final long serialVersionUID = 1L;

@OneToMany (cascade=CascadeType.PERSIST)
private List<span></span> storeCollection;

...

To persist a new user you call the persist method in the UserDAO :

public class UserDAO {

  @PersistenceContext
  private EntityManager em;

  public void save(User user{
    em.persist(user);
  }
}

public class CoreServiceImpl implements CoreService {

  @Autowired
  private UserDAO userDAO;

  public void saveUser() {
    User user = new User();
    user.getStoreCollection().add(new Store());
    userDAO.save(user);
  }
}

Since we have set cascade=CascadeType.PERSIST in our annotation, the new store object will be automatically inserted in database.

This is a great feature but when using it you must be aware that your are going to lose the control of a part of your application code : you should have created a StoreDAO with a save method to explicitly persist Store object.

The way I see DAO is that it’s allow you be loosely coupled with your data access api : you don’t need to know that it’s using iBatis, direct JDBC, etc … and another promise is to potentially allow you to switch from an implementation to another without having to change the code of your service layer.

This is this last promise which is not true any more if you start using the transitive persistence feature given by JPA and many others ORM framework.

Advertisements
Categories: java Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: