网上有很多封装的不错的baseDao,但是不一定适合,所以把自己用了这段时间的baseDao拿出来,一方面自己以后用着方便,一方面大家有需要可以拿去用;
因为此类封装完毕还有些方法没有在实际生产中使用过,所以如果有bug,或者建议可以回复我,我有时间就会修正;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Id;
import javax.persistence.Transient;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
/**@version 20151231
* SuperBaseDaoImpl中主要实现和数据库相关的操作逻辑,不涉及和视图层或控制层的一些操作;
* 其它dao可以继承此dao然后扩展;
* @author tingfeng
* 1.get时主要返回单个对象;
* 2.find使用的hql语句进行操作,主要返回list;
*/
@SuppressWarnings("unchecked")
public abstract class SuperBaseDaoImpl{
private Session session;
public abstract SessionFactory getSessionFactory();
/**
* 返回当前的Session,如果为null,返回SessionFactory的CurrentSession;
* @return
*/
public Session getCurrentSession() {
if(session!=null)
return session;
return this.getSessionFactory().getCurrentSession();
}
/**
* 此时获取当前session,不是从SessionFactory中取Session,可能为null;
* 如果需要从SessionFactory中取,用getCurrentSession()方法;
* @return
*/
public Session getBeanSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
/**
* 返回存储此对象的主键
*/
public Serializable save(T o){
return this.getCurrentSession().save(o);
}
public void saveByCollection(Collection collection){
for(T t:collection){
this.save(t);
}
}
public void update(T o) {
this.getCurrentSession().update(o);
}
public void saveOrUpdate(T o) {
this.getCurrentSession().saveOrUpdate(o);
}
/**更新一个实体中指定的字段
* 这里columnNames和columnsValues的名字和值得顺序必须一致;
* @param t
* @param columnNames
* @param columnValues
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws SecurityException
* @throws NoSuchFieldException
*/
public void updateByColumns(T t,List columnNames,List> columnValues) throws NoSuchFieldException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
String tableNameString=t.getClass().getSimpleName();
String hqlString="update "+tableNameString+" table_ set ";
for(int i=0;i void updateByExceptColumns(T t,List exceptColumnNames,List> columnValues) throws NoSuchFieldException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
List columnNames=this.getEntityColumnNames(t.getClass(), exceptColumnNames);
String tableNameString=t.getClass().getSimpleName();
String hqlString="update "+tableNameString+" table_ set ";
for(int i=0;i T get(Class c, Serializable id) {
return (T) this.getCurrentSession().get(c,id);
}
public T get(String hql) {
return this.get(hql, null);
}
public T get(String hql, Map params) {
Query q = this.getCurrentSession().createQuery(hql);
this.setParameterToQuery(q, params);
List l = q.list();
if (l != null && l.size() > 0) {
return l.get(0);
}
return null;
}
public void delete(T o) {
this.getCurrentSession().delete(o);
}
/**
* 从数据库中找出此id对象并删除
* @param entityClass
* @param id
*/
public void delete(Class entityClass, PK id) {
getCurrentSession().delete(get(entityClass, id));
}
/**hql语句,"delete from "+tableName+" where "+columnName+" in ("+columnValues+")"
* 用in语句删除指定表中,包含有指定值得指定列的记录;
* @param tableName
* @param columnName
* @param columnValues 如1,3,4这种in语句参数需要的内容
* @throws Exception
*/
public void deleteByColumns(String tableName,String columnName,String columnValues) throws Exception {
if(com.tingfeng.sql.utils.SqlUtils.sqlValidate(columnValues)){
throw new Exception("列名字数据中包含sql关键字!");
}
String hql="delete from "+tableName+" where "+columnName+" in ("+columnValues+")";
this.executeHql(hql);
}
/**
* hql语句,"delete from "+tableName+" where "+columnName+" in ("+columnValues+")"
* 用in语句删除指定表中,包含有指定值得指定列的记录;
* @param tableName
* @param columnName
* @param columnValues 一个参数值的集合
*/
public void deleteByColumns(String tableName,String columnName,Collection> columnValues) {
String hql="delete from "+tableName+" where "+columnName+" in (:columnValues)";
Map params=new HashMap();
params.put("columnValues",columnValues);
this.executeHql(hql,params);
}
/**
* 如果有id并存在于数据库中,则更新,否则保存
* @param model
*/
public void merge(T model) {
getCurrentSession().merge(model);
}
public List findList(String hql) {
Query q = this.getCurrentSession().createQuery(hql);
return q.list();
}
public List findList(String hql, Map params) {
Query q = this.getCurrentSession().createQuery(hql);
this.setParameterToQuery(q, params);
return q.list();
}
/**
*
* @param hql
* @param topCount 返回前topCount条记录
* @return
*/
public List findTopList(String hql, int topCount) {
// 获取当前页的结果集
Query query = this.getCurrentSession().createQuery(hql);
query.setFirstResult(0);
if(topCount<0) topCount=0;
query.setMaxResults(topCount);
return query.list();
}
/**
* 用hql语句,得到当前表的所有记录
* @param tableName
* @return
*/
public List findAll(String tableName){
String hqlString="select * from "+tableName;
return this.findList(hqlString);
}
/**
*
* @param hql
* @param params
* @param page 当前页码
* @param rows 每页显示的记录数量
* @return
*/
public List findList(String hql, Map params, int page, int rows) {
Query q = this.getCurrentSession().createQuery(hql);
this.setParameterToQuery(q, params);
if(page<1) page=1;
if(rows<0) rows=0;
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
}
public List findList(String hql, int page, int rows) {
return this.findList(hql, null, page,rows);
}
public Long getCountByHql(String hql) {
Query q = this.getCurrentSession().createQuery(hql);
return (Long) q.uniqueResult();
}
public Long getCountByHql(String hql, Map params) {
Query q = this.getCurrentSession().createQuery(hql);
this.setParameterToQuery(q, params);
return (Long) q.uniqueResult();
}
/**
* 根据HQL语句返回一个值,如分布获取总页数
*/
public Object getCountByHql(String hql, Object... params) {
Query query = getCurrentSession().createQuery(hql);
this.setParameterToQuery(query, params);
return query.uniqueResult();
}
/**
* 根据HQL语句,获得查找总记录数的HQL语句 如: select ... from Orgnization o where o.parent is
* null 经过转换,可以得到: select count(*) from Orgnization o where o.parent is null
* @param hql
* @return
*/
protected String getCountQuery(String hql) {
int index = hql.toLowerCase().indexOf("from");
int last = hql.toLowerCase().indexOf("order by");
if (index != -1) {
if (last != -1) {
return "select count(*) " + hql.substring(index, last);
}
return "select count(*) " + hql.substring(index);
}
return null;
}
public int executeHql(String hql) {
Query q = this.getCurrentSession().createQuery(hql);
return q.executeUpdate();
}
public int executeHql(String hql, Map params) {
Query q = this.getCurrentSession().createQuery(hql);
this.setParameterToQuery(q, params);
return q.executeUpdate();
}
public int executeHql(String hql,Object... objects) {
Query q = this.getCurrentSession().createQuery(hql);
this.setParameterToQuery(q, objects);
return q.executeUpdate();
}
/**
*
* @param hql
* @param objects 参数,其顺序应该和?占位符一一对应
* @return
*/
public int executeHql(String hql,List> objects) {
Query q = this.getCurrentSession().createQuery(hql);
this.setParameterToQuery(q, objects);
return q.executeUpdate();
}
/**
* @param q
* @param params 当前支持普通对象,数组,集合三种类型的参数
*/
protected void setParameterToQuery(Query q,Map params){
if (params != null && !params.isEmpty()) {
for (String key : params.keySet()) {
if(params.get(key) instanceof Object[]){
Object[] objs=(Object[]) params.get(key);
q.setParameterList(key, objs);
}else if(params.get(key) instanceof Collection>){
Collection> collection=(Collection>) params.get(key);
q.setParameterList(key, collection);
}else{
q.setParameter(key, params.get(key));
}
}
}
}
/**
* @param q
* @param params 当前支持普通对象,不支持集合与数组
*/
protected void setParameterToQuery(Query q,Object... params){
if (params != null && params.length>0) {
for (int i=0;i params){
if (params != null && !params.isEmpty()) {
for (int i=0;i T getCountBySql(String sql) {
return this.getCountBySql(sql,new HashMap());
}
/**
* 根据SQL语句返回一个值,如分布获取总页数
*/
public T getCountBySql(String sql, Object... params) {
Query query = getCurrentSession().createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
this.setParameterToQuery(query, params);
return (T) query.uniqueResult();
}
/**
* 根据SQL语句返回一个值,如分布获取总页数
*/
public T getCountBySql(String sql,Map params) {
Query query = getCurrentSession().createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
this.setParameterToQuery(query, params);
return (T) query.uniqueResult();
}
public List