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); } }