Code review and Dao optimization--BaseDao

Reflection: .java to .class, to get .class

  • Class.forName(…)
  • “ClassName”.class
  • “object”.getClass(), this method is in class “Object”

Generic: <>–typeof


Dao optimization:

  • New interface “BaseDao” and its implementing class “BaseDaoImpl”
    1
    2
    3
    4
    5
    6
    7
    public interface BaseDao<T> {
    void add(T t);
    void update(T t);
    void delete(T t);
    T findById(int id);
    List<T> findAll();
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {
private Class pClass;
public BaseDaoImpl() {
// get running class which one extends BaseDaoImpl, here is
// CustomerDaoImpl
Class clazz = this.getClass();
// get BaseDaoImpl<Customer>, import java.lang.reflect.Type
Type type = clazz.getGenericSuperclass();
ParameterizedType pType = (ParameterizedType) type;
// get <Customer>
Type[] types = pType.getActualTypeArguments();
Class tClass = (Class) types[0];
pClass = tClass;
}
public void add(T t) {
this.getHibernateTemplate().save(t);
}
public void update(T t) {
this.getHibernateTemplate().update(t);
}
public void delete(T t) {
this.getHibernateTemplate().delete(t);
}
// cannot code like T.class
public T findById(int id) {
// return (T) this.getHibernateTemplate().get(T.class, id);
return (T) this.getHibernateTemplate().get(pClass, id);
}
public List<T> findAll() {
// return this.getHibernateTemplate().find("from ", T);
return (List<T>) this.getHibernateTemplate().find("from " + pClass.getSimpleName());
}
}
  • Let normal interface Dao to extends BaseDao, then I can delete repetitive methods in normal interface Dao file.
    public interface CustomerDao extends BaseDao<Customer>{...} // here CustomerDao is a concrete interface
  • Let normal class Dao to extends BaseDaoImpl, then I can delete repetitive methods in normal class Dao file. The normal class do not need to extends HibernateDaoSupport because it has been done in BaseDaoImpl.
    public class CustomerDaoImpl extends BaseDaoImpl<Customer> implements CustomerDao{...}
    here CustomerDaoImpl is a concrete class