การใช้ hibernate สำหรับทำ ORM นั้น ยังมีข้อดีอีกอย่างนึงคือ
สามารถสร้าง generic dao ได้ โดยสามารถนำ operation ที่ใช้ทั่วไปคือ CRUD (Create, Read, Update, Delete)
มาไว้ที่ base-class โดยที่ไม่ต้องเขียน operation เหล่านี้ที่ sub-class อีก
แต่การทำแบบนี้เป็น type-unsafe operation คือ ใน base-class สามารถรับ parameter เป็น Object
หรือ base-class ของ data class เท่านั้น ซึ่งในการเรียกใช้งาน operation เหล่านี้เราต้องทำ explicit casting และ error บางอย่าง
สามารถตรวจสอบได้ที่ runtime เท่านั้น
ที่นี้เรามาดูการใช้ hibernate และ jdk5 ในการสร้าง generic type-safe dao กัน
ขั้นตอนแรกคือการกำหนด interface สำหรับ generic dao และ implementation class
public interface GenericDao <T, PK extends Serializable> {
public PK create(T object);
public T read(PK pk);
public void update(T object);
public void delete(T object);
}
public class GenericDaoImpl <T, PK extends Serializable>
implements GenericDao<T,PK> {
private Class<T> type;
public GenericDaoImpl(Class<T> type) {
this.type = type;
}
public PK create(T object) {
return (PK) getSession().save(object);
}
public T read(PK pk) {
return (T) getSession().get(type, pk);
}
public void update(T object) {
getSession().update(object);
}
public void delete(T object) {
getSession().delete(object);
}
}
ในการนำ GenericDao นี้ไปใช้งานต่างๆ ก็เพียงแค่สร้าง sub-class ขึ้นมาเท่านั้น
และยังสามารถเพิ่มเติม method ต่างๆ ตามที่ต้องการได้
public class PersonDao extends GenericDaoImpl<Person, Integer> {
public PersonDao() {
super(Person.class);
}
public List<Person> findByName(String name) {
return (List<Person>) getSession().createQuery("from packagename.Person p where p.name = ?").setString(1,name).list();
}
// additional finder methods if need
}