Hello,
There was a discussion about implementing DAOs using Java 5.0 generics in CaveatEmptor forum.
See
http://forum.hibernate.org/viewtopic.php?t=941256
I think it would be very useful if hbm2java could also create DAO code
and interface (interface might be optional, since users might want just construct DAOs without using factory)
for each entity using that generic DAO. All it needs to know is an entity class and entity's id class. This would save a lot of manual work writting DAOs looking like this:
Code:
public class UserHibernateDAO extends GenericHibernateDAO<User, Long> implements UserDAO {
public UserDAO() {
super(User.class, Long.class);
}
// end of hbm2java generated code
// here you can add business oriented finder methods, etc
}
public interface UserDAO extends GenericDAO<User, Long> {
// here you can add business oriented finder methods, etc
}
Below is an illustration of Generic DAO:
Code:
public abstract class GenericHibernateDAO<T extends Serializable, K extends Serializable>
implements GenericDAO<T, K> {
private Class<T> persistentClass;
private Class<K> idClass;
protected Session currentSession() {
return HibernateUtil.currentSession();
}
/**
* Constructor
*
* @param persistentClass
* @param idClass
*/
public GenericDAO(Class<T> persistentClass, Class<K> idClass) {
this.persistentClass = persistentClass;
this.idClass = idClass;
currentSession().beginTransaction();
}
/**
* @return Returns the idClass.
*/
public Class<K> getIdClass() {
return idClass;
}
/**
* @return Returns the persistentClass.
*/
public Class<T> getPersistentClass() {
return persistentClass;
}
/**
* Persist entity in database
*
* @param entity
*/
public T makePersistent(T entity) {
Session session = null;
try {
session = currentSession();
session.saveOrUpdate(entity);
} catch (HibernateException ex) {
throw new DaoException(ex);
}
return entity;
}
// other CRUD methods ...
I thought it would be a good idea to post it in this forum,
and someone might be interested in adding such functionality
to hibernate hbm2java or some other java code generation tool.
Thanks,
--MG
[/url]