DAO设计模式
源代码
Dao.java
public interface Dao<T> {
void add(T t);
void update(T t);
void delete(Serializable id);
T findOne(Serializable id);
}
CustomerDao.java
public interface CustomerDao extends Dao<Customer>{
List<Customer> findCustomers(int startIndex,int offset);
}
DaoImpl.java
这个是实现类,类中方法是Hibernate中的,可以删除
public abstract class BaseDao<T> implements Dao<T> {
private Class clazz;//查询的是哪个实体类
public BaseDao(){
//知道子类到底操作的是什么类型的JavaBean。即给clazz赋值
Type type = this.getClass().getGenericSuperclass();// new BookDaoImpl(); BaseDao<Book>
ParameterizedType ptype = (ParameterizedType)type;// BaseDao<Book>
Type types[] = ptype.getActualTypeArguments();// Book
clazz = (Class)types[0];
// System.out.println(clazz);
}
public void add(T t) {
Session s = HibernateUtil.getSession();
Transaction tx = s.beginTransaction();
s.save(t);
tx.commit();
s.close();
}
public T findOne(Serializable id) {
Session s = HibernateUtil.getSession();
return (T) s.get(clazz, id);
}
public void update(T t) {
Session s = HibernateUtil.getSession();
Transaction tx = s.beginTransaction();
s.update(t);
tx.commit();
s.close();
}
public void delete(Serializable id) {
T bean = findOne(id);
Session s = HibernateUtil.getSession();
Transaction tx = s.beginTransaction();
s.delete(bean);
tx.commit();
s.close();
}
}
CustomerDaoImpl.java
public class CustomerDaoImpl extends BaseDao<Customer> implements CustomerDao {
public List<Customer> findCustomers(int startIndex, int offset) {
return null;
}
}