我一直在尝试在休眠中完全理解和实现一个 GenericDAO 层。我对这个概念很陌生,并且一直在做一些阅读和研究。我在 GenericDAO 层的示例实现中找到了许多示例,这就是我最终得到的。
public class GenericDAOImpl<T, ID extends Serializable> implements GenericDAO<T, ID> {
private static Logger log = Logger.getLogger(GenericDAOImpl.class.getName());
private SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
public T findById(long id, Class<T> objectClass) {
log.info("Entered GenericDAOImpl findById(" + id +")");
T result = (T) getSessionFactory().getCurrentSession().load(objectClass, id);
if(result != null){
Hibernate.initialize(result);
return result;
}else{
return null;
}
}
public boolean create(T newInstance) {
log.info("Entered GenericDAOImpl create()");
if(newInstance == null){
return false;
}
getSessionFactory().getCurrentSession().saveOrUpdate(newInstance);
return true;
}
public boolean updpate(T updateInstance) {
log.info("Entered GenericDAOImpl updpate()");
if(updateInstance == null){
return false;
}
getSessionFactory().getCurrentSession().update(updateInstance);
return true;
}
public boolean delete(T entity) {
log.info("Entered GenericDAOImpl delete()");
if(entity == null){
return false;
}
getSessionFactory().getCurrentSession().delete(entity);
return true;
}
@SuppressWarnings("unchecked")
public List<T> findByExample(T exampleInstance, Class<T> objectClass){
log.info("Entered GenericDAOImpl findByExample()");
Criteria searchCriteria = getSessionFactory().getCurrentSession().createCriteria(objectClass);
searchCriteria.add(Example.create(exampleInstance));
return (List<T>)searchCriteria.list();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
似乎这在理论上应该可行(可能需要一些调整)
我的问题是我可以使用通用service
并view layer
“通过”分层架构方法吗?我对休眠事务的了解不够充分,无法知道这样做是否安全,以及它对事务的处理等......
例如,对于服务层来说可能是这样的
public class GenericServiceImpl<T, ID extends Serializable> implements GenericService<T, ID>{
private GenericDAO<T, ID> genericDao;
@Override
public T findById(long id, Class<T> objectClass) {
return this.getGenericDao().findById(id, objectClass);
}
@Override
public boolean create(T newInstance) {
return this.getGenericDao().create(newInstance);
}
@Override
public boolean updpate(T updateInstance) {
return this.getGenericDao().updpate(updateInstance);
}
@Override
public boolean delete(T entity) {
return this.getGenericDao().delete(entity);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public List findByExample(T exampleInstance, Class<T> objectClass) {
return this.getGenericDao().findByExample(exampleInstance, objectClass);
}
public GenericDAO<T, ID> getGenericDao() {
return genericDao;
}
public void setGenericDao(GenericDAO<T, ID> genericDao) {
this.genericDao = genericDao;
}
}
那么我可以继续做一个通用视图层吗?
Please let me know if this approach is acceptable or if there are any concerns with this approach.
Thanks in advance for your thoughts and responses!