I am trying to create a good pattern for my application. I want to reduce as much as possible the duplicate code and I want to use generics as much as possible. I have created a pattern for this but I want to know is there anything wrong with the code or if is there any other better pattern already made for this.
BaseDao interface:
public interface BaseDao<T extends DTO> {
List<T> fetchAll();
}
BaseImplementetion: all the DAO classes will extend this class.
public abstract class BaseDaoImpl<T extends DTO> implements BaseDao {
private Class<T> clazz;
public BaseDaoImpl(Class<T> clazz) {
this.clazz = clazz;
}
@Override
public List<T> fetchAll() {
List<T> entities = null;
Session session = null;
try {
session = doOpenSession();
Query<T> query = session.createQuery("from " + clazz.getName());
entities = query.list();
} catch (Exception e) {
throw e;
} finally {
session.close();
}
return entities;
}
UserDao interface:
public interface UserDao extends BaseDao{
User getUserByUsername(String username);
}
UserDao implementation:
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao{
public UserDaoImpl() {
this(User.class);
}
private UserDaoImpl(Class<User> clazz) {
super(clazz);
}
public User getUserByUsername(String name) {
User user = null;
try (Session session = HibernateUtils.getSessionFactory().openSession()) {
String hql = "FROM User u WHERE u.username = :name";
Query<User> query = session.createQuery(hql).setMaxResults(1);
query.setParameter("name", name);
user = query.uniqueResult();
}
return user;
}
}
Aucun commentaire:
Enregistrer un commentaire