//1、必须实现的接口
package com.lanou.mp.dao;
import java.io.Serializable;
import java.util.List;
public interface IBaseDao {
public <A> A getOneByID(Class<A> type,Serializable id );
public <A> List<A> getAll(String hql, List<String> parm);
public <A> List<A> findByPage(String hql,int page,int count);
public <A> boolean insert(A a);
}
//2、实现了接口的工具类
package com.lanou.mp.util;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import com.lanou.mp.dao.IBaseDao;
public class HibernateBaseDao implements IBaseDao {
private static Configuration config;
private static SessionFactory sf;// 全系统只有一个,同servlet
static {
config = new Configuration().configure();
sf = config.buildSessionFactory();
}
/**
* 这个方法用来根据id查询
*/
@Override
public <A> A getOneByID(Class<A> type, Serializable id) {
Session session = sf.getCurrentSession();
Transaction tx = session.beginTransaction();
A a = session.get(type, id);
tx.commit();
return a;
}
/**
* 这个方法用来条件查询的
*/
@Override
public <A> List<A> getAll(String hql, List<String> parm) {
Session session = sf.getCurrentSession();
Transaction tx = session.beginTransaction();
Query<A> query = session.createQuery(hql);
for (int i = 0; i < parm.size(); i++) {
query.setParameter(i, parm.get(i));
}
List<A> list = query.getResultList();// 转化成集合
tx.commit();
return list;
}
/**
* 分页的方法
*/
@Override
public <A> List<A> findByPage(String hql, int page, int count) {
Session session = sf.getCurrentSession();
Transaction tx = session.beginTransaction();
Query<A> query = session.createQuery(hql);
query.setMaxResults(count);// 显示的条数
query.setFirstResult(page);// 从第几条记录开始
List<A> list = query.getResultList();// 转化成集合
tx.commit();
return list;
}
/**
* 这个方法用来插入的
*/
@Override
public <A> boolean insert(A a) {
Session session = sf.getCurrentSession();
Transaction tx = session.beginTransaction();
session.save(a.getClass());
tx.commit();
return true;
}
}