Dao层和Service层设计

1、Dao接口层

public interface IBaseDao<T, ID extends Serializable>{
   public abstract Serializable save(T t);
    /*其他接口*/
}

2、StudentDao接口层

public interface IStudentDao extends IBaseDao<Student,Serializable> {
  /*只有特殊的接口才在这里声明*/
}

3、BaseDao实现层

为了让BaseDaoImpl实现大部分的数据操作逻辑,必须要从泛型T获取实际的领域对象的类型,关键是理解getGenericSuperclass。

getGenericSuperclass() :

通过反射获取当前类表示的实体(类,接口,基本类型或void)的直接父类的Type,这里如果打印genType,结果为

com.huawei.happycar.dao.impl.BaseDaoImpl<com.huawei.happycar.domain.Student, java.io.Serializable>

getActualTypeArguments():

返回参数数组,参数中的第一个就是我们需要的领域对象类,打印entryClass,结果为

class com.huawei.happycar.domain.Student

再说一遍:

当我们在StudentServerImpl中初始化StudentDaoImpl的时候,会默认初始化调用这个BaseDaoImpl。

此时getClass就是:com.huawei.happycar.dao.impl.StudentDaoImpl

其父类为:com.huawei.happycar.dao.impl.BaseDaoImpl<com.huawei.happycar.domain.Student, java.io.Serializable>,这里要求该父类必须带泛型参数,否则报错

 Constructor threw exception; nested exception is java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

接下来,从第一个泛型参数强制转换一下,就得到了领域对象Student。

public class BaseDaoImpl<T, ID extends Serializable> implements IBaseDao<T, ID> {
/*自动注入factory*/ @Autowired private SessionFactory sessionFactory; protected Class<T> entityClass;
/*获取第一个泛型类的参数,以确定实体类型*/
public BaseDaoImpl() { Type genType = getClass().getGenericSuperclass(); Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); entityClass = (Class) params[0]; } /*sessionFactory*/ public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * 需要开启事物,才能得到CurrentSession */ public Session getSession() { Session session = null; try { session = sessionFactory.getCurrentSession(); } catch(HibernateException ex) { session = sessionFactory.openSession(); } return session; }
/*具体接口实现*/
......
}

 4、StudentDao实现层

@Repository("studentDaoImplBean")
public class StudentDaoImpl extends BaseDaoImpl<Student, Serializable> implements IStudentDao{
    /*只实现特殊的接口*/
}

5、Service接口

public interface StudentService {
    Serializable saveStudent(Student student);
    List<Student> listAllStudent();
    Page<Student> getSutdentPage(String currentPageNum);
}

 6、Service实现

@Service("studentServiceBean")
public class StudentServiceImpl implements StudentService {
    /*自动注入*/
    @Autowired
    public StudentDaoImpl studentDaoImpl;

    @Override
    public Serializable saveStudent(Student student) {
        return studentDaoImpl.save(student); 
  } 
}
原文地址:https://www.cnblogs.com/mingziday/p/4663233.html