許多Java開發員已經知道DAO模式。這個模式有許多不同的實現,盡管如此,在這篇文章中將闡述DAO實現的設想:
1.系統中所有數據庫訪問都通過DAO來包裝
2.每個DAO實例代表一個原生的領域對象或實體。如果一個領域對象有一個獨立的生命周期,那么它應該有自己的DAO。
3.DAO代表在領域對象上的CURD操作。
4.DAO允許基于Criteria的查詢不同于用主鍵查詢。我比較傾向構造一個finder方法。該finder方法的返回值是一個領域對象組的Collection集合
5.DAO不代表處理事務,Sessions或連接。這些在DAO外處理將更加靈活。
例子:
GenericDao是CRUD操作的DAO基類。
public?interface?GenericDao?<T,?PK?extends?Serializable>?{
????/**?Persist?the?newInstance?object?into?database?*/
????PK?create(T?newInstance);
????/**?Retrieve?an?object?that?was?previously?persisted?to?the?database?using
?????*???the?indicated?id?as?primary?key
?????*/
????T?read(PK?id);
????/**?Save?changes?made?to?a?persistent?object.??*/
????void?update(T?transientObject);
????/**?Remove?an?object?from?persistent?storage?in?the?database?*/
????void?delete(T?persistentObject);
}
下面是它的實現類:
public?class?GenericDaoHibernateImpl?<T,?PK?extends?Serializable>
????implements?GenericDao<T,?PK>,?FinderExecutor?{
????private?Class<T>?type;
????public?GenericDaoHibernateImpl(Class<T>?type)?{
????????this.type?=?type;
????}
????public?PK?create(T?o)?{
????????return?(PK)?getSession().save(o);
????}
????public?T?read(PK?id)?{
????????return?(T)?getSession().get(type,?id);
????}
????public?void?update(T?o)?{
????????getSession().update(o);
????}
????public?void?delete(T?o)?{
????????getSession().delete(o);
????}
}
擴展GenericDAO
public?interface?PersonDao?extends?GenericDao<Person,?Long>?{
????List<Person>?findByName(String?name);
}