I agree with your points, and this would be true if Hibernate DAO methods used their own session and returned detached objects. But if the Hibernate session is tied to the transaction (by using, for example, the Spring SessionFactoryUtils), the objects returned by DAOs are attached objects, similar to entity beans. This means that all the changes I could make on the returned objects will be persisted transparently in the database (which would not be the case with JDBC-based DAOs). This also means that navigating into the object graph will work with Hibernate-based DAOs, because Hibernate will load the associated objects lazily, which will not happen with JDBC-based objects.
So, there are two solutions:
- make Hibernate-based DAOs that return detached objects, as would JDBC-based DAOs. This makes me lose performance, ease of development, but allows me to migrate to any other DAO implementation
- make Hibernate-based DAOs that return attached objects, similar to entity beans, which allow me to use Hibernate to its full power and makes development much easier, but doesn't allow me to easily switch to another DAO implementation.
To make it clearer, the second solution allows me to do this to associate a new group to a user:
Code:
User user = userDAO.load(userId);
Group group = groupDAO.load(groupId);
user.getGroups().add(group);
whereas with the first solution, I would have to do:
Code:
User user = userDAO.load(userId);
Group group = groupDAO.load(groupId);
Set userGroups = groupDAO.getGroupsForUser(user);
if (!userGroups.contains(group)) {
userDAO.addGroupToUser(user, group);
}