com.lynn.dao.BaseDao.java Source code

Java tutorial

Introduction

Here is the source code for com.lynn.dao.BaseDao.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lynn.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.lynn.util.PageResults;

@Repository
@SuppressWarnings("unchecked")
public class BaseDao<T, PK extends java.io.Serializable> {

    // ??
    private Class<T> entityClass;

    @Autowired
    protected SessionFactory sessionFactory;

    public BaseDao() {
        this.entityClass = null;
        Class<?> c = getClass();
        Type type = c.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
            this.entityClass = (Class<T>) parameterizedType[0];
        }
    }

    @Resource
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

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

    /*
     * ?ID?PO
    */
    public T get(PK id) {
        Assert.notNull(id, "id is required");
        return (T) getSession().get(entityClass, id);
    }

    /*
     * ?PO
    */
    public PK save(T entity) {
        Assert.notNull(entity, "entity is required");
        return (PK) getSession().save(entity);
    }

    /*
     * ?PO
    */
    public void saveOrUpdate(T entity) {
        getSession().saveOrUpdate(entity);
    }

    /*
     * PO
    */
    public void update(T entity) {
        getSession().update(entity);
    }

    /*
     * ?idPO
    */
    public void delete(PK id) {
        getSession().delete(this.get(id));
    }

    /*
     * PO
    */
    public void deleteObject(T entity) {
        getSession().delete(entity);
    }

    /*
     * ?idPO?
    */
    public boolean exists(PK id) {
        return get(id) != null;
    }

    /*
     * ?idPO
    */
    public T load(PK id) {
        return (T) getSession().load(this.entityClass, id);
    }

    /*
     * 
    */
    public void deleteAll(Collection<?> entities) {
        if (entities == null)
            return;
        for (Object entity : entities) {
            getSession().delete(entity);
        }
    }

    /**
     * @param <T> ?
     * @param sql  sql?
     * @param param ?
     * @return
     */
    @SuppressWarnings("hiding")
    public <T> List<T> queryByHql(String sql, Object... param) {
        List<T> list = new ArrayList<T>();
        Query query = getSession().createQuery(sql);
        if (param != null) {
            for (int i = 0; i < param.length; i++) {
                query.setParameter(i, param[i]);
            }
        }
        list = query.list();
        return list;
    }

    /**
     * <?HQL>
     * @param hql HQL?
     * @param values ??Object
     * @return 
     */
    public Long countByHql(String hql, Object... values) {
        Query query = this.getSession().createQuery(hql);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return (Long) query.uniqueResult();
    }

    /**
     * <?HQL>
     * @param hql HQL?
     * @param values ??Object
     * @return ?
     */
    public Double countByHQLDouble(String hql, Object... values) {
        Query query = this.getSession().createQuery(hql);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return (Double) query.uniqueResult();
    }

    /**
     * ?SQL
     * @param sql
     * @param values
     * @return
     */
    public BigInteger countBySql(String sql, Object... values) {
        Query query = this.getSession().createSQLQuery(sql);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return (BigInteger) query.uniqueResult();
    }

    /**
     * <HQL>
     * @param hql HQL?
     * @param countHql ?HQL?
     * @param pageNo 
     * @param pageSize ?
     * @param values ?Object?
     * @return PageResults???????List?
     */
    public PageResults<T> findPageByFetchedHql(String hql, String countHql, int pageNo, int pageSize,
            Object... values) {
        PageResults<T> retValue = new PageResults<T>();
        Query query = this.getSession().createQuery(hql);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        int currentPage = pageNo > 1 ? pageNo : 1;
        retValue.setCurrentPage(currentPage);
        retValue.setPageSize(pageSize);
        if (countHql == null) {
            ScrollableResults results = query.scroll();
            results.last();
            retValue.setTotalCount(results.getRowNumber() + 1);// 
        } else {
            Long count = countByHql(countHql, values);
            retValue.setTotalCount(count.intValue());
        }
        retValue.resetPageNo();
        List<T> itemList = query.setFirstResult((currentPage - 1) * pageSize).setMaxResults(pageSize).list();
        if (itemList == null) {
            itemList = new ArrayList<T>();
        }
        retValue.setResults(itemList);

        return retValue;
    }

    /**
     * <Hql?>
     * @param hqlString hql
     * @param values ??
     * @see com.itv.launcher.util.IBaseDao#queryHql(java.lang.String, java.lang.Object[])
     */
    public void executeHql(String hqlString, Object... values) {
        Query query = this.getSession().createQuery(hqlString);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        query.executeUpdate();
    }

    /**
     * <Sql?>
     * @param sqlString sql
     * @param values ??
     * @see com.itv.launcher.util.IBaseDao#querySql(java.lang.String, java.lang.Object[])
     */
    public void executeSql(String sqlString, Object... values) {
        Query query = this.getSession().createSQLQuery(sqlString);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        query.executeUpdate();
    }

    /**
     * <?HQL?>
     * @param hqlString HQL?
     * @param values ??Object
     * @return 
     * @see com.itv.launcher.util.IBaseDao#getByHQL(java.lang.String, java.lang.Object[])
     */
    public T getByHQL(String hqlString, Object... values) {
        Query query = this.getSession().createQuery(hqlString);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return (T) query.uniqueResult();
    }

    /**
     * <?SQL?>
     * @param sqlString SQL?
     * @param values ??Object
     * @return 
     * @see com.itv.launcher.util.IBaseDao#getBySQL(java.lang.String, java.lang.Object[])
     */
    public T getBySQL(String sqlString, Object... values) {
        Query query = this.getSession().createSQLQuery(sqlString);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return (T) query.uniqueResult();
    }

    /**
     * <?HQL?list>
     * @param hqlString HQL?
     * @param values ??Object
     * @return List?
     * @see com.itv.launcher.util.IBaseDao#getListByHQL(java.lang.String, java.lang.Object[])
     */
    public List<T> getListByHQL(String hqlString, Object... values) {
        Query query = this.getSession().createQuery(hqlString);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return query.list();
    }

    /**
     * <?SQL?list>
     * @param sqlString HQL?
     * @param values ??Object
     * @return List?
     * @see com.itv.launcher.util.IBaseDao#getListBySQL(java.lang.String, java.lang.Object[])
     */
    @SuppressWarnings("rawtypes")
    public List getListBySQL(String sqlString, Object... values) {
        Query query = this.getSession().createSQLQuery(sqlString);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return query.list();
    }

    /**
     * SQL?List<Map>
     * select id,name from member.
    * @author WKX
    * @param sql
    * @param values
    * @since 2016112 ?3:32:17
    */
    public List<Map<String, Object>> getListMapBySQL(String sql, Object... values) {
        SQLQuery query = this.getSession().createSQLQuery(sql);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String, Object>> result = query.list();
        return result;
    }
}