一、Dao接口層java
public interface IBaseDao<T, ID extends Serializable>{ public abstract Serializable save(T t); /*其餘接口*/ }
二、StudentDao接口層數組
public interface IStudentDao extends IBaseDao<Student,Serializable> { /*只有特殊的接口才在這裏聲明*/ }
三、BaseDao實現層session
爲了讓BaseDaoImpl實現大部分的數據操做邏輯,必需要從泛型T獲取實際的領域對象的類型,關鍵是理解getGenericSuperclass。app
getGenericSuperclass() :dom
經過反射獲取當前類表示的實體(類,接口,基本類型或void)的直接父類的Type,這裏若是打印genType,結果爲ide
com.huawei.happycar.dao.impl.BaseDaoImpl<com.huawei.happycar.domain.Student, java.io.Serializable>this
getActualTypeArguments():spa
返回參數數組,參數中的第一個就是咱們須要的領域對象類,打印entryClass,結果爲code
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; }
/*具體接口實現*/
......
}
四、StudentDao實現層
@Repository("studentDaoImplBean") public class StudentDaoImpl extends BaseDaoImpl<Student, Serializable> implements IStudentDao{ /*只實現特殊的接口*/ }
五、Service接口
public interface StudentService { Serializable saveStudent(Student student); List<Student> listAllStudent(); Page<Student> getSutdentPage(String currentPageNum); }
六、Service實現
@Service("studentServiceBean") public class StudentServiceImpl implements StudentService { /*自動注入*/ @Autowired public StudentDaoImpl studentDaoImpl; @Override public Serializable saveStudent(Student student) { return studentDaoImpl.save(student); } }