hibernate dao代码

来源:互联网 发布:炫彩软件 编辑:程序博客网 时间:2024/06/16 22:47
package com.tempus.modules.orm.hibernate;


import java.io.Serializable;
import java.sql.Connection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import org.hibernate.Criteria;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.BetweenExpression;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.LikeExpression;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.impl.CriteriaImpl.Subcriteria;
import org.hibernate.metadata.ClassMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;


import com.tempus.modules.utils.ReflectionUtils;


/**
 * 封装Hibernate原生API的CRUD泛型基类.
 * 
 * 可在Service层直接使用,也可以扩展泛型DAO子类使用.
 * 参考Spring2.5自带的Petlinc例子,取消了HibernateTemplate,直接使用Hibernate原生API.
 * 
 * @param <T>
 *            DAO操作的对象类型


 * @param <PK>
 *            主键类型
 * 
 * @author andy
 */
@SuppressWarnings("unchecked")
public class SimpleHibernateDao<T, PK extends Serializable> {


protected Logger logger = LoggerFactory.getLogger(getClass());


protected SessionFactory sessionFactory;


protected Class<T> entityClass;


/**
* 用于扩展的DAO子类使用的构造函数.

* 通过子类的泛型定义取得对象类型Class. eg. public class UserDao extends SimpleHibernateDao<User,
* Long>
*/
public SimpleHibernateDao() {
this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass());
}


/**
* 用于Service层直接使用SimpleHibernateDAO的构造函数. eg. SimpleHibernateDao<User,
* Long> userDao = new SimpleHibernateDao<User, Long>(sessionFactory,
* User.class);
*/
public SimpleHibernateDao(final SessionFactory sessionFactory,
final Class<T> entityClass) {
this.sessionFactory = sessionFactory;
this.entityClass = entityClass;
}


public SessionFactory getSessionFactory() {
return sessionFactory;
}


/**
* 采用@Autowired按类型注入SessionFactory,当有多个SesionFactory的时候Override本函数.

* @param sessionFactory
*/
@Autowired
public void setSessionFactory(final SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}


public Session getSession() {
return sessionFactory.getCurrentSession();
}


/**
* 保存新增或修改的对象.
*/
public void saveOrUpdate(final T entity) {
Assert.notNull(entity, "entity不能为空");
getSession().saveOrUpdate(entity);
logger.debug("save entity: {}", entity);
}
/**
* 保存新增或修改的对象.
*/
public void saveOrUpdateObject(final Object entity) {
Assert.notNull(entity, "entity不能为空");
getSession().saveOrUpdate(entity);
logger.debug("save entity: {}", entity);
}
/**
* save对象
* @param entity
*/
public void update(final T entity) {
        Assert.notNull(entity, "entity不能为空");
        getSession().merge(entity);
        logger.debug("save entity: {}", entity);
    }
    /**
     * save对象
     * @param entity
     */
    public void realupdate(final T entity) {
        Assert.notNull(entity, "entity不能为空");
        getSession().update(entity);
        logger.debug("save entity: {}", entity);
    }
/**
* update对象
* @param entity
*/
public void save(final T entity) {
Assert.notNull(entity, "entity不能为空");
getSession().save(entity);
logger.debug("save entity: {}", entity);
}
/**
* 删除对象.

* @param entity
*            对象必须是session中的对象或含id属性的transient对象.
*/
public void delete(final T entity) {
Assert.notNull(entity, "entity不能为空");
getSession().delete(entity);
logger.debug("delete entity: {}", entity);
}


/**
* 按id删除对象.
*/
public void delete(final PK id) {
Assert.notNull(id, "id不能为空");
delete(get(id));
logger.debug("delete entity {},id is {}", entityClass.getSimpleName(),
id);
}


/**
* 按id获取对象.
*/
public T get(final PK id) {
Assert.notNull(id, "id不能为空");
try {
return (T) getSession().load(entityClass, id);
} catch (ObjectNotFoundException ex) {
// 未查到数据时不输出出错信息


logger.info("**********未找到数据!**********");
}
return null;


}
/**
* 按id获取对象.
*/
public T realget(final PK id) {
Assert.notNull(id, "id不能为空");
try {
return (T) getSession().get(entityClass, id);
} catch (ObjectNotFoundException ex) {
// 未查到数据时不输出出错信息


logger.info("**********未找到数据!**********");
}
return null;


}


/**
* 获取全部对象.
*/
public List<T> getAll() {
return find();
}


/**
* 按属性查找对象列表,匹配方式为相等.
*/
public List<T> findBy(final String propertyName, final Object value) {
Assert.hasText(propertyName, "propertyName不能为空");
Criterion criterion = Restrictions.eq(propertyName, value);
return find(criterion);
}


/**
* 按属性查找唯一对象,匹配方式为相等,对象必须唯一.
*/
public T findByUnique(final String propertyName, final Object value) {
Assert.hasText(propertyName, "propertyName不能为空");
Criterion criterion = Restrictions.eq(propertyName, value);
return (T) createCriteria(criterion).uniqueResult();
}
/**
* 按属性查找唯一对象,匹配方式为相等,如果出现多个,返回第一个.
*/
public T findByFirstOne(final String propertyName, final Object value) {
Assert.hasText(propertyName, "propertyName不能为空");
Criterion criterion = Restrictions.eq(propertyName, value);
return  createCriteria(criterion).list().size()>0?(T)createCriteria(criterion).list().get(0):null;
}
public T findByFirstOneMultProtertynames(final String[] propertyNames, final Object[] values) { 
Criteria criteria = getSession().createCriteria(this.entityClass);
for(int i=0;i<propertyNames.length;i++)
{
Criterion criterion = Restrictions.eq(propertyNames[i], values[i]);
criteria.add(criterion);
}
List list = criteria.list();
return  list.size()>0?(T)list.get(0):null;
}
/**
* 按HQL查询对象列表.

* @param values
*            数量可变的参数


*/
public List<T> find(final String hql, final Object... values) {
return createQuery(hql, values).list();
}
public List<Object> findListObject(final String hql, final Object... values) {
return createQuery(hql, values).list();
}
/**
* 按HQL查询对象列表.

* @param hql
*            数量可变的参数


*/
public List<T> find(final String hql) {
return createQuery(hql).list();
}
 


/**
* 按HQL查询对象列表.

* @param values 命名参数,按名称绑定.
*/
public <X> List<X> find(final String hql, final Map<String, ?> values) {
return createQuery(hql, values).list();
}
/**
* 按HQL查询唯一对象.
*/
public Object findUniqueObject(final String hql, final Object... values) {
return createQuery(hql, values).uniqueResult();
}
/**
* 按HQL查询唯一对象.
*/
public T findUnique(final String hql, final Object... values) {
return (T)createQuery(hql, values).uniqueResult();
}

/**
* 按HQL查询唯一对象.
*/
public T findUniqueByMul(final String hql, final Object... values) {
List<T> lst  = createQuery(hql, values).list(); 
return lst.size()>0?(T)lst.get(0):null;
}

/**
* 按HQL查询Integer类型结果.
*/
public Integer findInt(final String hql, final Object... values) {
return (Integer) findUnique(hql, values);
}
/**
* 按HQL查询Integer类型结果.
*/
public Object findObject(final String hql, final Object... values) {
return  findUnique(hql, values);
}
/**
* 按HQL查询Integer类型结果.
*/
public Integer findInt(final String hql) {
return (Integer) findUnique(hql);
}
/**
* 按HQL查询Long类型结果.
*/
public Long findLong(final String hql, final Object... values) {
return (Long) findUnique(hql, values);
}


/**
* 按HQL查询Long类型结果.
*/
public Long findLong(final String hql) {
return (Long) findUnique(hql);
}
/**
* 按HQL查询Long类型结果.
*/
public String findString(final String hql) {
return (String) findUnique(hql);
}
/**
* 根据查询HQL与参数列表创建Query对象.

* 返回对象类型不是Entity时可用此函数灵活查询.

* @param values
*            数量可变的参数


*/
public Query createQuery(final String queryString, final Object... values) {
Assert.hasText(queryString, "queryString不能为空");
Query query = getSession().createQuery(queryString); 
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return query;
}


/**
* 按Criteria查询对象列表.

* @param criterions
*            数量可变的Criterion.
*/
public List<T> find(final Criterion... criterions) {
return createCriteria(criterions).list();
}
/**
* 判断是否建立关联
* @param impl
* @param path
* @return
*/
public String getAlias(CriteriaImpl impl, String path) {
  Iterator iterator = impl.iterateSubcriteria();
  for (; iterator.hasNext();) {
   Subcriteria subcriteria = (Subcriteria) iterator.next();
   if (subcriteria.getPath().equals(path)) {
    return subcriteria.getAlias();
   }
                               }
  return null;
}
/**
* 根据Criterion条件创建Criteria.

* 返回对象类型不是Entity时可用此函数灵活查询.

* @param criterions
*            数量可变的Criterion.
*/
public Criteria createCriteria(final Criterion... criterions) {
Criteria criteria = getSession().createCriteria(entityClass); 
try{
for (Criterion c : criterions) {
String propertyName="";
if(c instanceof SimpleExpression)
{
SimpleExpression se = (SimpleExpression)c; 
propertyName  = se.getPropertyName();
}
if(c instanceof BetweenExpression)
{
BetweenExpression se = (BetweenExpression)c; 
propertyName  = se.getPropertyName();
}
if(c instanceof LikeExpression)
{
LikeExpression se = (LikeExpression)c; 
propertyName  = se.getPropertyName();
}
 




if(!"".equals(propertyName))
{
  if(propertyName.indexOf(".")>0)
  {
  String master = propertyName.split("\\.")[0];
  String alias = getAlias((CriteriaImpl) criteria, master);
  if (alias == null)//判断是否建立关联
  {
  criteria.createAlias(master, master);
  }
  }
}
criteria.add(c);
}
}catch(Exception ex)
{
ex.printStackTrace();
}
return criteria;
}


/**
* 判断对象的属性值在数据库内是否唯一.

* 在修改对象的情景下,如果属性新修改的值(value)等于属性原来的值(orgValue)则不作比较.
*/
public boolean isPropertyUnique(final String propertyName,
final Object newValue, final Object orgValue) {
if (newValue == null || newValue.equals(orgValue))
return true;
Object object = findByUnique(propertyName, newValue);
return (object == null);
}


/**
* 取得对象的主键名.
*/
public String getIdName() {
ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
Assert.notNull(meta, "Class " + entityClass.getSimpleName()
+ " not define in HibernateSessionFactory.");
return meta.getIdentifierPropertyName();
}


/**
* 获取连接

* @return
* @throws Exception
*/


public Connection getConnection() throws Exception {
return this.getSession().connection();
}
/**
* 按原生SQL查询对象列表.

* @param sql
*            数量可变的参数


*/
public List<T> findBySql(final String sql) {
  Session session = this.getSession();
  List<T> catNameList = null;
  try {
    catNameList = session.createSQLQuery(sql).addEntity(entityClass).list();
   return catNameList ;
  }catch(Exception ex)
  {
  ex.printStackTrace();
  } 
return catNameList;

public List<Object> findBySQL(final String sql) {
  Session session = this.getSession();
  List<Object> catNameList = null;
  try {
    catNameList = session.createSQLQuery(sql).list();
   return catNameList ;
  }catch(Exception ex)
  {
  ex.printStackTrace();
  } 
return catNameList;

public List<Object[]> findBySQLObjectArray(final String sql) {
  Session session = this.getSession();
  List<Object[]> catNameList = null;
  try {
    catNameList = session.createSQLQuery(sql).list();
   return catNameList ;
  }catch(Exception ex)
  {
  ex.printStackTrace();
  } 
return catNameList;

/**
* 按原生SQL查询对象列表.

* @param sql
*            数量可变的参数


*/
public Object findUniqueBySql(final String sql) {
  Session session = this.getSession();
  Object result = null;
  try {
  result = session.createSQLQuery(sql).uniqueResult();
   return result ;
  }catch(Exception ex)
  {
  ex.printStackTrace();
  } 
return result;
}
/**
* 按id获取对象.
*/
public T getData(final PK id) {
Assert.notNull(id, "id不能为空");
try {
return (T) getSession().get(entityClass, id);
} catch (ObjectNotFoundException ex) {
// 未查到数据时不输出出错信息


logger.error("**********未找到数据!**********",ex);
}
return null;


}


/**
* 执行HQL进行批量修改/删除操作.
*/
public int batchExecute(final String hql, final Object... values) {
return createQuery(hql, values).executeUpdate();
}


/**
* 执行HQL进行批量修改/删除操作.
* @return 更新记录数.
*/
public int batchExecute(final String hql, final Map<String, ?> values) {
return createQuery(hql, values).executeUpdate();
}


}
原创粉丝点击