论坛首页 Java企业应用论坛

帮看看这个dao

浏览 7247 次
该帖已经被评为隐藏帖
作者 正文
   发表时间:2011-05-30  
先批评下你的代码规范
0 请登录后投票
   发表时间:2011-05-30  
我把我的贴出来,你可以参考参考。
package com.test.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.test.bean.Pager;
import com.test.bean.Search;
import com.test.bean.Pager.OrderType;

/**
 * Dao接口实现 - 基类实现
 * =======================================
 * @author  作者姓名:
 * @version 创建时间:Apr 8, 2011 5:30:19 PM
 * =======================================
 */
@Component
public class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK> {

	private Class<T> entityClass;
	protected SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {
		this.entityClass = null;
		//得到类的Class
        Class c = getClass();
        //返回本类的父类,包含泛型参数信息
        Type type = c.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
            this.entityClass = (Class<T>) parameterizedType[0];
        }
	}

	/**
	 * 设置SessionFactory
	 * @param sessionFactory - Hibernate的SessionFactory
	 */
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * 得到当前Session
	 * @return Session - Hibernate的Session
	 */
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	/**
	 * 保存实体对象
	 * @param entity - 实体
	 * @return PK - 实体分配后的ID
	 */
	@SuppressWarnings("unchecked")
	public PK save(T entity) {
		Assert.notNull(entity, "entity is required");
		return (PK)getSession().save(entity);
	}
	
	/**
	 * 根据ID获取实体对象(get方式)
	 * @param id - 实体id
	 * @return T - 实体对象
	 */
	@SuppressWarnings("unchecked")
	public T get(PK id) {
		Assert.notNull(id, "id is required");
		return (T)getSession().get(entityClass, id);
	}
	
	/**
	 * 根据ID获取实体对象(load方式)
	 * @param id - id
	 * @return T - 实体对象
	 */
	@SuppressWarnings("unchecked")
	public T load(PK id) {
		Assert.notNull(id, "id is required");
		return (T)getSession().load(entityClass, id);
	}
	
	/**
	 * 删除实体对象
	 * @param entity - 实体对象
	 */
	public void delete(T entity) {
		Assert.notNull(entity, "entity is required");
		getSession().delete(entity);
	}
	
	/**
	 * 删除实体对象
	 * @param id - id
	 */
	public void delete(PK id) {
		Assert.notNull(id, "entity is required");
		T entity = load(id);
		getSession().delete(entity);
	}
	
	/**
	 * 更改实体对象
	 * @param entity - 实体对象
	 */
	public void update(T entity) {
		Assert.notNull(entity, "entity is required");
		getSession().update(entity);
	}
	
	/**
	 * 根据ID数组获取实体对象集合.
	 * @param ids - id数组
	 * @return List - 实体集合
	 */
	@SuppressWarnings("unchecked")
	public List<T> get(PK[] ids) {
		Assert.notEmpty(ids, "ids must not be empty");
		String hql = "from " + entityClass.getName() + " as model where model.id in(:ids)";
		return getSession().createQuery(hql).setParameterList("ids", ids).list();
	}
	
	/**
	 * 根据属性名和属性值获取实体对象
	 * @param propertyName - 属性名
	 * @param value - 属性值
	 * @return T - 对象
	 */
	@SuppressWarnings("unchecked")
	public T get(String propertyName, Object value) {
		Assert.hasText(propertyName, "propertyName must not be empty");
		Assert.notNull(value, "value is required");
		String hql = "from " + entityClass.getName() + " as model where model." + propertyName + " = ?";
		return (T) getSession().createQuery(hql).setParameter(0, value).uniqueResult();
	}
	
	/**
	 * 根据属性名和属性值获取实体对象集合
	 * @param propertyName - 属性名
	 * @param value - 属性值
	 * @return List - 对象集合
	 */
	@SuppressWarnings("unchecked")
	public List<T> getList(String propertyName, Object value) {
		Assert.hasText(propertyName, "propertyName must not be empty");
		Assert.notNull(value, "value is required");
		String hql = "from " + entityClass.getName() + " as model where model." + propertyName + " = ?";
		return getSession().createQuery(hql).setParameter(0, value).list();
	}
	
	/**
	 * 获取所有实体对象集合
	 * @return List - 实体集合
	 */
	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		String hql = "from " + entityClass.getName();
		return getSession().createQuery(hql).list();
	}
	
	/**
	 * 获取所有实体对象总数.
	 * @return long - 实体对象总数
	 */
	public Long getTotalCount() {
		String hql = "select count(*) from " + entityClass.getName();
		return (Long) getSession().createQuery(hql).uniqueResult();
	}
	
	/**
	 * 根据ID数组删除实体对象
	 * @param ids - id数组
	 */
	public void delete(PK[] ids) {
		Assert.notEmpty(ids, "ids must not be empty");
		for (PK id : ids) {
			T entity = load(id);
			getSession().delete(entity);
		}
	}
	
	/**
	 * 根据Pager对象进行查询
	 * @param pager - 页面bean
	 * @return Pager - 页面bean
	 */
	public Pager findByPager(Pager pager) {
		if (pager == null) {
			pager = new Pager();
		}
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entityClass);
		return findByPager(pager, detachedCriteria);
	}
	
	/**
	 * 根据Pager和DetachedCriteria对象进行查询
	 * @param pager - 页面bean
	 * @param detachedCriteria - Hibernate的detachedCriteria
	 * @return Pager - 页面bean
	 */
	public Pager findByPager(Pager pager, DetachedCriteria detachedCriteria) {
		if (pager == null) {
			pager = new Pager();
		}
		Integer pageNumber = pager.getPageNumber();
		Integer pageSize = pager.getPageSize();
		String property = pager.getProperty();
		String keyword = pager.getKeyword();
		String orderBy = pager.getOrderBy();
		OrderType orderType = pager.getOrderType();
		
		Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
		if (StringUtils.isNotEmpty(property) && StringUtils.isNotEmpty(keyword)) {
			String propertyString = "";
			if (property.contains(".")) {
				String propertyPrefix = StringUtils.substringBefore(property, ".");
				String propertySuffix = StringUtils.substringAfter(property, ".");
				criteria.createAlias(propertyPrefix, "model");
				propertyString = "model." + propertySuffix;
			} else {
				propertyString = property;
			}
			criteria.add(Restrictions.like(propertyString, "%" + keyword + "%"));
		}
		
		Integer totalCount = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
		
		criteria.setProjection(null);
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		criteria.setFirstResult((pageNumber - 1) * pageSize);
		criteria.setMaxResults(pageSize);
		if (StringUtils.isNotEmpty(orderBy) && orderType != null) {
			if (orderType == OrderType.asc) {
				criteria.addOrder(Order.asc(orderBy));
			} else {
				criteria.addOrder(Order.desc(orderBy));
			}
		}
		pager.setTotalCount(totalCount);
		pager.setList(criteria.list());
		return pager;
	}
	
	
	/**
	 * 根据Search和Pager来查询
	 * @param search - 查询bean
	 * @param pager - 页面bean
	 * @return Pager - 页面bean
	 */
	public Pager searchByProperty(Search search, Pager pager){
		
		if (pager == null) {
			pager = new Pager();
		}
		if (search == null) {
			search = new Search();
		}
		Integer pageNumber = pager.getPageNumber();
		Integer pageSize = pager.getPageSize();
		String orderBy = pager.getOrderBy();
		OrderType orderType = pager.getOrderType();
		
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entityClass);
		Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
		//循环取得条件(字符串类型)
		if(search.getStrProperty()!=null){
			for(int i=0; i < search.getStrProperty().size(); i++){
				String propertyStr = search.getStrProperty().get(i);
				String keywordStr = search.getStrKeyword().get(i);
				if (StringUtils.isNotEmpty(propertyStr) && StringUtils.isNotEmpty(keywordStr)) {
					criteria.add(Restrictions.like(propertyStr, "%" + keywordStr + "%"));
				}
			}
		}
		//循环取得条件(日期类型)
		if(search.getDateProperty()!=null){
			for(int i=0; i < search.getDateProperty().size(); i++){
				String propertyDate = search.getDateProperty().get(i);
				Date dateFrom = search.getDateFrom().get(i);
				Date dateTo = search.getDateTo().get(i);
				if (dateFrom != null && !"".equals(dateFrom) && dateTo != null && !"".equals(dateTo)) {
					criteria.add(Restrictions.between(propertyDate, dateFrom, dateTo));
				}
			}
		}
		//循环取得条件(整数类型)
		if(search.getIntProperty()!=null){
			for(int i=0; i < search.getIntProperty().size(); i++){
				String propertyInt = search.getIntProperty().get(i);
				Object intFrom = search.getIntFrom().get(i);
				Object intTo = search.getIntTo().get(i);
				if (intFrom != null && intTo != null) {
					criteria.add(Restrictions.between(propertyInt, intFrom, intTo));
				}
			}
		}
		
		Integer totalCount = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
		criteria.setProjection(null);
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		criteria.setFirstResult((pageNumber - 1) * pageSize);
		criteria.setMaxResults(pageSize);
		//设定排序规则
		if (StringUtils.isNotEmpty(orderBy) && orderType != null) {
			if (orderType == OrderType.asc) {
				criteria.addOrder(Order.asc(orderBy));
			} else {
				criteria.addOrder(Order.desc(orderBy));
			}
		}
		pager.setTotalCount(totalCount);
		pager.setList(criteria.list());
		
		return pager;
	}
	
	/**
	 * 刷新session.
	 */
	public void flush() {
		getSession().flush();
	}

	/**
	 * 清除Session
	 */
	public void clear() {
		getSession().clear();
	}

	/**
	 * 清除某一对象.
	 */
	public void evict(Object object) {
		Assert.notNull(object, "object is required");
		getSession().evict(object);
	}
	
	/**
	 * 根据属性名、修改前后属性值判断在数据库中是否唯一(若新修改的值与原来值相等则直接返回true).
	 * @param propertyName	属性名称
	 * @param oldValue		修改前的属性值
	 * @param oldValue		修改后的属性值
	 * @return boolean
	 */
	public boolean isUnique(String propertyName, Object oldValue, Object newValue) {
		Assert.hasText(propertyName, "propertyName must not be empty");
		Assert.notNull(newValue, "newValue is required");
		if (newValue == oldValue || newValue.equals(oldValue)) {
			return true;
		}
		if (newValue instanceof String) {
			if (oldValue != null && StringUtils.equalsIgnoreCase((String) oldValue, (String) newValue)) {
				return true;
			}
		}
		T object = get(propertyName, newValue);
		return (object == null);
	}

	/**
	 * 根据属性名判断数据是否已存在.
	 * @param propertyName	属性名称
	 * @param value			值
	 * @return boolean
	 */
	public boolean isExist(String propertyName, Object value) {
		Assert.hasText(propertyName, "propertyName must not be empty");
		Assert.notNull(value, "value is required");
		T object = get(propertyName, value);
		return (object != null);
	}
	
}


0 请登录后投票
   发表时间:2011-05-30  
这样的式的没法看。。。
0 请登录后投票
   发表时间:2011-05-30  
鼓励自己造轮子!继续加油!
0 请登录后投票
   发表时间:2011-05-30  
steafler 写道
建议不要用泛型



为什么啊?求解释,谢谢
0 请登录后投票
   发表时间:2011-05-30  
whaosoft 写道
1年的写个这个不错了

....还在我上大学的时候,类似的这个封装我已经写过啦
0 请登录后投票
   发表时间:2011-05-30  
一团糟的代码,很蛋疼的啊
0 请登录后投票
   发表时间:2011-05-30  
不出意外的话,楼主要被扣分了。哈哈
这代码谁能看懂啊,太乱了
0 请登录后投票
   发表时间:2011-05-30  
瞅瞅我这个。。。。。
public class ProductDaoImpl implements ProductDao {
	private HibernateTemplate template;
	public HibernateTemplate getTemplate() {
		return template;
	}
	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}

	public void deleteProduct(Product product) {
		template.delete(product);
	}

	public void insertProduct(Product product) {
		template.save(product);
	}

	@SuppressWarnings("unchecked")
	public List<Product> queryAllProducts() {
		return template.find("from Product");
	}

	public Product queryProductById(Integer id) {
		return (Product)template.get(Product.class, id);
		
	}

	@SuppressWarnings("unchecked")
	public List<Product> queryProductByName(final String productName) {
		return (List<Product>)template.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q=session.createQuery("from Product as p where p.productName = ? ");
				q.setString(0, productName);
				return q.list();
			}	
		});
	}

	@SuppressWarnings("unchecked")
	public List<Product> queryProductByStatus(final Status status) {
		return (List<Product>)template.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q=session.createQuery("from Product as p where p.status.id = ? ");
				q.setInteger(0, status.getId());
				return q.list();
			}
		});
	}

	public void updateProduct(Product product) {
		template.update(product);
	}
	@SuppressWarnings("unchecked")
	public List<Product> queryProductByProductType(final ProductType productType) {
		return (List<Product>)template.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q=session.createQuery("from Product as p where p.productType.id=? ");
				q.setInteger(0, productType.getId());
				return q.list();
			}
		});
	}
	
	@SuppressWarnings("unchecked")
	public List<Product> queryAllProducts(final PageModel page) {
		Long size=(Long)template.find("select count(*) from Product as p order by p.id").get(0);
		page.setTotalCount(size.intValue());
		return (List<Product>)template.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q=session.createQuery("from Product as p order by p.id");
				q.setFirstResult(page.getFirstResult());
				q.setMaxResults(page.getPageSize());
				return q.list();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public List<Product> queryProductByName(final PageModel page,final String productName) {	
		return (List<Product>)template.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q1=session.createQuery("select count(*) from Product as p where p.productName = ? order by p.id");
				q1.setString(0, productName);
				page.setTotalCount(q1.executeUpdate());
				Query q2=session.createQuery("from Product as p where p.productName = ? order by p.id");
				q2.setString(0, productName);
				q2.setFirstResult(page.getFirstResult());
				q2.setMaxResults(page.getPageSize());
				return q2.list();
			}});
	}

	@SuppressWarnings("unchecked")
	public List<Product> queryProductByProductType(final PageModel page,
			final ProductType productType) {
		return (List<Product>)template.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q1=session.createQuery("select count(*) from Product as p where p.productType.id = ? order by p.id");
				q1.setInteger(0, productType.getId());
				page.setTotalCount(q1.executeUpdate());
				Query q2=session.createQuery("from Product as p where p.productType.id = ? order by p.id");
				q2.setInteger(0, productType.getId());
				q2.setFirstResult(page.getFirstResult());
				q2.setMaxResults(page.getPageSize());
				return q2.list();
			}});
	}

	@SuppressWarnings("unchecked")
	public List<Product> queryProductByStatus(final PageModel page,final Status status) {	
		return (List<Product>)template.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q1=session.createQuery("select count(*) from Product as p where p.status.id = ? order by p.id");
				q1.setInteger(0, status.getId());
				page.setTotalCount(q1.executeUpdate());
				Query q2=session.createQuery("from Product as p where p.status.id = ? order by p.id");
				q2.setInteger(0, status.getId());
				q2.setFirstResult(page.getFirstResult());
				q2.setMaxResults(page.getPageSize());
				return q2.list();
			}});
	}
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics