hibernate 使用

简介:     package org.slave4j.utils; import java.util.ArrayList; import java.util.List; import java.

 

 

package org.slave4j.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.slave4j.orm.Compositor;
import org.slave4j.orm.Filtration;
import org.slave4j.orm.PageData;
import org.slave4j.orm.Filtration.MatchType;
import org.slave4j.orm.Compositor.CompositorType;
import org.slave4j.orm.hibernate.BaseEntity;
import org.springframework.util.Assert;

/**
 * hibernate工具类
 *  
 */
public class HibernateUtils
{
	/**
	 * 根据Criterion条件创建Criteria.
	 */
	public static Criteria createCriteria(Session session, Class<? extends BaseEntity> entityClass,
			Criterion... criterions)
	{
		Criteria criteria = session.createCriteria(entityClass);
		for (Criterion criterion : criterions)
		{
			criteria.add(criterion);
		}
		return criteria;
	}

	/**
	 * 根据查询HQL与参数列表创建Query对象.
	 */
	public static Query createQuery(Session session, String hql, Object... values)
	{
		Assert.hasText(hql, "hql不能为空");
		Query query = session.createQuery(hql);

		for (int i = 0; i < values.length; i++)
		{
			query.setParameter(i, values[i]);
		}

		return query;
	}

	/**
	 * 根据查询HQL与参数列表创建Query对象.
	 */
	public static Query createQuery(Session session, String hql, Map<String, ?> values)
	{
		Assert.hasText(hql, "hql不能为空");
		Query query = session.createQuery(hql);
		if (values != null)
		{
			query.setProperties(values);
		}
		return query;
	}

	/**
	 * 创建Criterion
	 */
	private static Criterion createCriterion(String fieldName, Object fieldValue, MatchType matchType)
	{
		Criterion criterion = null;
		Assert.hasText(fieldName, "fieldName不能为空");
		switch (matchType)
		{
			case EQ: // =
				criterion = Restrictions.eq(fieldName, fieldValue);
				break;
			case LIKE: // like
				criterion = Restrictions.like(fieldName, (String) fieldValue, MatchMode.ANYWHERE);
				break;
			case LT: // <
				criterion = Restrictions.lt(fieldName, fieldValue);
				break;
			case LE: // <=
				criterion = Restrictions.le(fieldName, fieldValue);
				break;
			case GT: // >
				criterion = Restrictions.gt(fieldName, fieldValue);
				break;
			case GE: // >=
				criterion = Restrictions.ge(fieldName, fieldValue);
				break;
		}
		return criterion;
	}

	/**
	 * 执行count查询获得本次Criteria查询所能获得的对象总数.
	 */
	@SuppressWarnings("unchecked")
	private static long countCriteriaResult(Criteria criteria)
	{
		CriteriaImpl impl = (CriteriaImpl) criteria;

		// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
		Projection projection = impl.getProjection();
		ResultTransformer resultTransformer = impl.getResultTransformer();

		List<CriteriaImpl.OrderEntry> orderEntries = null;
		orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries");
		ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());

		// 执行Count查询
		Object object = criteria.setProjection(Projections.rowCount()).uniqueResult();
		long totalCount = 0;
		if (object instanceof Integer)
		{
			totalCount = ((Integer) object).longValue();
		}
		else
		{
			totalCount = (Long) object;
		}

		// 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
		criteria.setProjection(projection);

		if (projection == null)
		{
			criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}
		if (resultTransformer != null)
		{
			criteria.setResultTransformer(resultTransformer);
		}

		ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);

		return totalCount;
	}

	/**
	 * 设置排序参数到Criteria对象
	 */
	public static Criteria setCompositorParameter(Criteria criteria, Compositor compositor)
	{
		if (compositor != null)
		{
			String fieldName = compositor.getFieldName();
			CompositorType compositorType = compositor.getCompositorType();
			switch (compositorType)
			{
				case ASC:
					criteria.addOrder(Order.asc(fieldName));
					break;
				case DESC:
					criteria.addOrder(Order.desc(fieldName));
					break;
			}
		}

		return criteria;
	}

	/**
	 * 设置过滤条件到Criteria对象
	 */
	public static Criteria setFiltrationParameter(Criteria criteria, Filtration... filtrations)
	{
		if (filtrations.length > 0)
		{
			List<Criterion> criterions = new ArrayList<Criterion>();
			for (Filtration filtration : filtrations)
			{
				Criterion criterion = null;
				if (!filtration.isMultiFilter())
				{
					criterion = createCriterion(filtration.getFieldName(), filtration.getFieldValue(), filtration
							.getMatchType());
					criterions.add(criterion);

				}
				else
				{
					// 包含多个属性需要比较的情况,进行or处理.
					Disjunction disjunction = Restrictions.disjunction();
					for (String filedName : filtration.getFieldNames())
					{
						criterion = createCriterion(filedName, filtration.getFieldValue(), filtration
								.getMatchType());
						disjunction.add(criterion);
					}
					criterions.add(disjunction);
				}
			}
			for (Criterion criterion : criterions)
			{
				criteria.add(criterion);
			}
		}

		return criteria;
	}

	/**
	 * 设置过滤条件到Criteria对象
	 */
	public static Criteria setFiltrationParameter(Criteria criteria, List<Filtration> filtrationList)
	{
		if (filtrationList != null)
		{
			// Filtration[] filtrations = (Filtration[]) filtrationList.toArray();
			Filtration[] filtrations = new Filtration[filtrationList.size()];
			for (int i = 0; i < filtrationList.size(); i++)
			{
				filtrations[i] = filtrationList.get(i);
			}
			return setFiltrationParameter(criteria, filtrations);
		}
		else
		{
			return criteria;
		}
	}

	/**
	 * 设置分页参数到Criteria对象
	 */
	public static Criteria setParameter(Criteria criteria, PageData<?> pageData)
	{
		// 第一步:设置查询条件
		setFiltrationParameter(criteria, pageData.getFiltrations());
		// 第二步:读取记录总数
		if (pageData.getPagination().isReadTotalCount())
		{
			long totalCount = countCriteriaResult(criteria);
			pageData.getPagination().setTotalCount(totalCount);
		}

		// 第三步:设置查询范围
		criteria.setFirstResult(pageData.getPagination().getCurrentlyPageFirstResoultIndex());
		criteria.setMaxResults(pageData.getPagination().getPageSize());

		// 排序条件
		setCompositorParameter(criteria, pageData.getCompositor());

		return criteria;
	}
}

 

 

 

package org.slave4j.orm.hibernate;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.slave4j.orm.Compositor;
import org.slave4j.orm.Filtration;
import org.slave4j.orm.PageData;
import org.slave4j.utils.HibernateUtils;
import org.slave4j.utils.ReflectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * dao基类.
 * 		1:该类封装了最常见数据库操作的方法,你可以继承该类,添加自己喜欢的方法
 * 		2:当你有多个sessionFactory时,你也可以在你的子类中重写setSessionFactory()方法
 * @param <T> 实体类类型
 */
@SuppressWarnings("unchecked")
public class BaseDao<T extends BaseEntity>
{
	protected Logger logger = LoggerFactory.getLogger(getClass());

	protected SessionFactory sessionFactory;

	protected Class<T> entityClass;

	/**
	 * 构造方法
	 */
	public BaseDao()
	{
		this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass());
	}

	/**
	 * 采用@Resource(name="xxx")按名称注入SessionFactory, 当有多个SesionFactory的时候Override本函数.
	 */
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	/**
	 * 取得Session.
	 */
	public Session getSession()
	{
		return sessionFactory.getCurrentSession();
	}

	//--------------------------------------------------------------------------------------------------

	/**
	 * 新增对象.
	 */
	public void save(T entity)
	{
		Assert.notNull(entity, "entity不能为空");
		entity.setInsertTime(new Date());//插入时间
		getSession().save(entity);
		logger.debug("save entity: {}", entity);
	}

	/**
	 * 修改对象.
	 */
	public void update(T entity)
	{
		Assert.notNull(entity, "entity不能为空");
		entity.setLastUpdateTime(new Date());//最后一次修改时间
		getSession().update(entity);
		logger.debug("update entity: {}", entity);
	}

	/**
	 * 删除对象.
	 */
	public void delete(T entity)
	{
		Assert.notNull(entity, "entity不能为空");
		getSession().delete(entity);
		logger.debug("delete entity: {}", entity);
	}

	/**
	 * 删除对象.
	 */
	public void delete(Integer id)
	{
		delete(find(id));
		logger.debug("delete entity {},id is {}", entityClass.getSimpleName(), id);
	}

	/**
	 * 对象显示.
	 */
	public void visible(Integer id)
	{
		T entity = find(id);
		Assert.notNull(entity, "entity不能为空");
		if(!entity.isVisible())
		{
			entity.setVisible(true);
			update(entity);
			logger.debug("visible entity {},id is {}", entityClass.getSimpleName(), id);
		}
	}

	/**
	 * 对象不显示.
	 */
	public void unVisible(Integer id)
	{
		T entity = find(id);
		Assert.notNull(entity, "entity不能为空");
		if(entity.isVisible())
		{
			entity.setVisible(false);
			update(entity);
			logger.debug("unVisible entity {},id is {}", entityClass.getSimpleName(), id);
		}
		
	}

	/**
	 * 按id获取对象.
	 */
	public T find(Integer id)
	{
		Assert.notNull(id, "id不能为空");
		return (T) getSession().load(entityClass, id);
	}

	/**
	 * 按属性查找唯一对象,匹配方式为相等.
	 */
	public T find(String fieldName, Object fieldValue)
	{
		Assert.hasText(fieldName, "fieldName不能为空");
		Criterion criterion = Restrictions.eq(fieldName, fieldValue);
		return (T) HibernateUtils.createCriteria(getSession(), entityClass, criterion).uniqueResult();
	}

	/**
	 * 按属性查找对象列表,匹配方式为相等.
	 */
	public List<T> findList(String fieldName, Object fieldValue)
	{
		Assert.hasText(fieldName, "fieldName不能为空");
		Criterion criterion = Restrictions.eq(fieldName, fieldValue);
		return HibernateUtils.createCriteria(getSession(), entityClass, criterion).list();
	}

	/**
	 * 按照过滤条件对象查找对象列表.
	 */
	public List<T> findList(Filtration... filtrations)
	{
		Criteria criteria = HibernateUtils.createCriteria(getSession(), entityClass);
		//设置过滤条件
		criteria = HibernateUtils.setFiltrationParameter(criteria, filtrations);
		return criteria.list();
	}

	/**
	 * 按照过滤条件对象查找对象列表.
	 */
	public List<T> findList(List<Filtration> filtrationList)
	{
		Criteria criteria = HibernateUtils.createCriteria(getSession(), entityClass);
		//设置过滤条件
		criteria = HibernateUtils.setFiltrationParameter(criteria, filtrationList);
		return criteria.list();
	}

	/**
	 * 按照过滤条件对象查找对象列表,支持排序.
	 */
	public List<T> findList(Compositor compositor, Filtration... filtrations)
	{
		Criteria criteria = HibernateUtils.createCriteria(getSession(), entityClass);
		//设置过滤条件
		criteria = HibernateUtils.setFiltrationParameter(criteria, filtrations);
		//设置排序
		criteria = HibernateUtils.setCompositorParameter(criteria, compositor);
		return criteria.list();
	}

	/**
	 * 按照过滤条件对象查找对象列表,支持排序.
	 */
	public List<T> findList(Compositor compositor, List<Filtration> filtrationList)
	{
		Criteria criteria = HibernateUtils.createCriteria(getSession(), entityClass);
		//设置过滤条件
		criteria = HibernateUtils.setFiltrationParameter(criteria, filtrationList);
		//设置排序
		criteria = HibernateUtils.setCompositorParameter(criteria, compositor);
		return criteria.list();
	}

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

	/**
	 * 获取全部对象,支持排序.
	 */
	public List<T> findAll(Compositor compositor)
	{
		return findList(compositor);
	}

	/**
	 * 分页查询.
	 */
	public PageData<T> find(PageData<T> pageData)
	{
		Assert.notNull(pageData, "pageData不能为空");
		Criteria criteria = HibernateUtils.createCriteria(getSession(), entityClass);
		HibernateUtils.setParameter(criteria, pageData);
		pageData.setResult(criteria.list());
		return pageData;
	}

	/**
	 * 按id列表获取对象.
	 */
	public List<T> findListByIds(List<Integer> idList)
	{
		if (idList != null && idList.size() >= 1)
		{
			Criterion criterion = Restrictions.in("id", idList);
			return HibernateUtils.createCriteria(getSession(), entityClass, criterion).list();
		} else
		{
			return null;
		}
	}

	//--------------------------------------------------------------------------------------------------

	/**
	 * 按HQL查询唯一对象.
	 * @param hql "from Users where name=? and password=?"
	 * @param values 数量可变的参数,按顺序绑定.
	 * @return
	 */
	public <X> X find(String hql, Object... values)
	{
		return (X) HibernateUtils.createQuery(getSession(), hql, values).uniqueResult();
	}

	/**
	 * 按HQL查询唯一对象.
	 * @param hql "from Users where name=:name and password=:password"
	 * @param values 命名参数,按名称绑定.
	 * @return
	 */
	public <X> X find(String hql, Map<String, ?> values)
	{
		return (X) HibernateUtils.createQuery(getSession(), hql, values).uniqueResult();
	}

	/**
	 * 按HQL查询对象列表.
	 * @param hql "from Users where name=? and password=?"
	 * @param values 数量可变的参数,按顺序绑定.
	 * @return
	 */
	public <X> List<X> findList(String hql, Object... values)
	{
		return HibernateUtils.createQuery(getSession(), hql, values).list();
	}

	/**
	 * 按HQL查询对象列表.
	 * @param hql "from Users where name=:name and password=:password"
	 * @param values 命名参数,按名称绑定.
	 * @return 
	 */
	public <X> List<X> findList(String hql, Map<String, ?> values)
	{
		return HibernateUtils.createQuery(getSession(), hql, values).list();
	}

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

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

	//--------------------------------------------------------------------------------------------------

	/**
	 * 本地SQL进行修改/删除操作.
	 * @return 更新记录数.
	 */
	public List find(String sql)
	{
		Assert.hasText(sql, "sql不能为空");
		return getSession().createSQLQuery(sql).list();
	}

}

 

 

使用方法

Compositor compositor = new Compositor("deliverWebRequest", CompositorType.DESC);
List<Filtration> filtrations = new  ArrayList<Filtration> ();
Filtration filtration = new Filtration(MatchType.EQ, 0, "logicDel");
filtrations.add(filtration);
l=((ShopDao) this.baseDao).findList(compositor, filtrations);

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。



 
 
 谢谢您的赞助,我会做的更好!

 

 

目录
相关文章
|
3月前
|
Java 数据库连接 API
|
SQL Java 关系型数据库
Hibernate的使用总结
Hibernate的使用总结
63 0
|
SQL Java 数据库连接
|
Java 数据库连接
|
Java 数据库连接 数据库
|
关系型数据库 Java 数据库连接
|
SQL Java 数据库连接