Hibernate Dao、Service 基类

来源:互联网 发布:stussy淘宝哪家正 编辑:程序博客网 时间:2024/06/03 12:35


package com.sys.core.base.dao;import java.io.Serializable;import java.util.List;import java.util.Map;import com.sys.core.Pagination;import com.sys.core.SqlBean;/** *  DAO 基类接口 * @date:2016年6月7日 * @param <E> 实体类 * @param <PK> 主键 */public interface IBaseDao<E, PK extends Serializable> {/** * 获得持久化对象的类型 *  * @return */Class<E> getClazz();/** * 保存对象 */void save(E e);/** * 删除对象 */void delete(E e);/** * 更新对象 *  * @param e */void update(E e);/** * 保存或更新 *  * @param e */void saveOrUpdate(E e);/** * 删除properyName == value 的记录 */void deleteByProperty(String propertyName, Object value);/** * 通过ID查询对象 * @param id 主键 * @return */E findById(PK id);/** * 获取当前对象的所有记录 * @ columns 需要返回的列名 * @ pagination 分页信息 * @return 所有记录 */List<E> findAll(String columns,Pagination pagination);/** * 通过多个属性查找 *  * @param propertyNames *            属性名称数组 * @param values *            属性值数组 * @return */List<E> findByPropertys(String columns,String[] propertyNames, Object[] values,Pagination pagination);/** * 通过多个属性查找 *  * @param propertyNames *            属性名称数组 * @param values *            属性值数组 * @return */List<E> findByProperty(String columns,String propertyName, Object value,Pagination pagination);/** * 通过多个属性模糊查找 *  * @param propertyNames *            属性名称数组 * @param values *            属性值数组 * @return */List<E> findByPropertysFuzzy(String columns,String[] propertyNames, Object[] values,Pagination pagination);/** * 通过某个属性模糊查找 *  * @param propertyName *            属性名称 * @param value *            属性值 * @return */List<E> findByPropertyFuzzy(String column,String propertyName, Object value,Pagination pagination);/** * 统计所有记录的总数 *  * @return 总数 */ int countAll();/** * 统计数据库中当1个或多个propertyName=value时的记录总数 *  * @param propertyNames * @param values * @return */int countByPropertys(String[] propertyNames, Object[] values);int countByPropertysFuzzy(String[] propertyNames, Object[] values);/** * 根据SQL查询记录数 */int  queryCountBySQL(SqlBean sql);int  mapCountByHQL(String hql,Object[] args);/** * 查找并通过某一属性排序 *  * @param property *            排序依据的顺序 * @param isSequence *            是否顺序排序 *//** * 根据SQL语法查询 *  * @param sql * @return */List<E> queryBySQL(SqlBean sql);/** * 根据SQL语法分页查询 *  * @param sql * @return */List<E> queryBySQL(SqlBean sql,Pagination pagination);/** * 根据SQL语法查询 * @param sql * @return 返回自定义的Map类型 */List<Map<String,Object>> queryMapByHQL(String hql,Object[] args,Pagination pagination);}


package com.sys.core.base.dao;import java.io.Serializable;import java.lang.reflect.ParameterizedType;import java.util.List;import java.util.Map;import org.hibernate.Query;import org.hibernate.SQLQuery;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import com.sys.core.Pagination;import com.sys.core.SqlBean;/** * 泛型DAO实现 *  * @date:2016年6月7日 * @param <E> * @param <PK> */@SuppressWarnings("unchecked")public class BaseDaoImpl<E, PK extends Serializable>  implements IBaseDao<E, PK> {@Autowiredprivate SessionFactory sessionFactory;private Class<E> clazz;public BaseDaoImpl() {clazz = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];}@Overridepublic Class<E> getClazz() {return clazz;} private String from() {return "from " + getClazz().getName();}private String count() {return "select count(1) " + from();}private String where(String[] propertyNames, Object[] values) {StringBuilder accum = new StringBuilder(" where 1 = 1");for (int i = 0, len = propertyNames.length; i < len; i++) {accum.append(" and ");if (values[i] instanceof String) {accum.append(propertyNames[i]).append("='").append(values[i]).append("'");} else {accum.append(propertyNames[i]).append("=").append(values[i]);}}return accum.toString();}// 模糊查询private String whereFuzzy(String[] propertyNames, Object[] values) {StringBuilder accum = new StringBuilder(" where 1 = 1");for (int i = 0, len = propertyNames.length; i < len; i++) {accum.append(" and ");if (values[i] instanceof String) {accum.append(propertyNames[i]).append(" like '%").append(values[i]).append("%'");} else {accum.append(propertyNames[i]).append("=").append(values[i]);}}return accum.toString();}public Session getSession() {return sessionFactory.getCurrentSession();}@Overridepublic void save(E e) {getSession().save(e);}@Overridepublic void update(E e) {getSession().update(e);}@Overridepublic void saveOrUpdate(E e) {getSession().saveOrUpdate(e);}@Overridepublic void delete(E e) {getSession().delete(e);}@Overridepublic void deleteByProperty(String propertyName, Object value) {List<E> es = findByProperty("",propertyName,value,null);for (E e : es) {delete(e);}}@Overridepublic E findById(PK id) {return (E) getSession().get(getClazz(), id);}@Overridepublic List<E> findAll(String columns, Pagination pagination) {String hql="";if(columns==null||columns.trim().equals("")){hql=from();}else{hql="SELECT "+columns+" "+from();}Query query = getSession().createQuery(hql);if (pagination != null) {query.setFirstResult(pagination.getStart());query.setMaxResults(pagination.getEnd());}return query.list();}@Overridepublic List<E> findByPropertys(String columns,String[] propertyNames, Object[] values, Pagination pagination) {String hql="";if(columns==null||columns.trim().equals("")){hql=from();}else{hql="SELECT "+columns+" "+from();}Query query = getSession().createQuery(hql + where(propertyNames, values));if (pagination != null) {query.setFirstResult(pagination.getStart());query.setMaxResults(pagination.getEnd());}return query.list();}@Overridepublic List<E> findByProperty(String columns,String propertyName, Object value, Pagination pagination) {String[] propertyNames = { propertyName };Object[] values = { value };return findByPropertys(columns,propertyNames, values, pagination);}@Overridepublic List<E> findByPropertysFuzzy(String columns,String[] propertyNames, Object[] values, Pagination pagination) {String hql="";if(columns==null||columns.trim().equals("")){hql=from();}else{hql="SELECT "+columns+" "+from();}Query query = getSession().createQuery(hql + whereFuzzy(propertyNames, values));if (pagination != null) {query.setFirstResult(pagination.getStart());query.setMaxResults(pagination.getEnd());}return query.list();}@Overridepublic List<E> findByPropertyFuzzy(String columns,String propertyName, Object value, Pagination pagination) {String[] propertyNames = { propertyName };Object[] values = { value };return findByPropertysFuzzy(columns,propertyNames, values, pagination);}@Overridepublic int countAll() {return Integer.valueOf(getSession().createQuery(count()).uniqueResult().toString()) ;}@Overridepublic int countByPropertys(String[] propertyNames, Object[] values) {Query query = getSession().createQuery(count() + where(propertyNames, values));return Integer.parseInt(query.uniqueResult().toString());}@Overridepublic int queryCountBySQL(SqlBean sql){Query query = getSession().createSQLQuery("SELECT COUNT(1) "+sql.getBody());//return Integer.parseInt(query.uniqueResult().toString());return Integer.parseInt(query.uniqueResult().toString());    }@Overridepublic List<E> queryBySQL(SqlBean sql) {     return queryBySQL(sql,null); }@Overridepublic List<Map<String, Object>> queryMapByHQL(String hql,Object[] args,Pagination pagination) {Session session = getSession();Query query = session.createQuery(hql);if (args != null && args.length > 0) {for (int i = 0; i < args.length; i++)query.setParameter(i, args[i]);}if (pagination != null) {query.setFirstResult(pagination.getStart());query.setMaxResults(pagination.getEnd());}List<Map<String, Object>> list=query.list();return list;}@Overridepublic int countByPropertysFuzzy(String[] propertyNames, Object[] values) {Query query = getSession().createQuery(count() + whereFuzzy(propertyNames, values));return Integer.parseInt(query.uniqueResult().toString());}@Overridepublic List<E> queryBySQL(SqlBean sql, Pagination pagination) {//SQLQuery query = getSession().createSQLQuery(sql.getHead()+" "+sql.getBottom()+" "+sql.getBottom()); SQLQuery query = getSession().createSQLQuery(sql.getHead()+" "+sql.getBody()+" "+sql.getBottom());if (pagination != null) {System.out.println("=====s======"+pagination.getStart());            System.out.println("=====e======"+pagination.getEnd());query.setFirstResult(pagination.getStart());query.setMaxResults(pagination.getEnd());}return query.list();}@Overridepublic int mapCountByHQL(String hql,Object[] args) {  Session session = getSession();Query query = session.createQuery(hql);if (args != null && args.length > 0) {for (int i = 0; i < args.length; i++)query.setParameter(i, args[i]);}return Integer.parseInt(query.list().get(0).toString());}}



package com.sys.core.base.service;import java.io.Serializable;import java.util.List;import java.util.Map;import com.sys.core.Pagination;import com.sys.core.SqlBean;import com.sys.core.response.ResponsePage;/** * Service 基类接口 *  * 2015年1月3日 */public interface IBaseService <E, PK extends Serializable> {     /**     * 不推荐使用全列查询除非必要(如:你当前无法知道有哪些列)     * 获取当前对象的所有记录的所有属性     * @return 所有记录     */@Deprecated    List<E> findAll() throws Exception;        /**     * 获取当前对象的所有记录(只返回指定的列,列名以“,”号隔开)     * @param columns 列名     * @return 所有记录     */    List<E> findAll(String columns) throws Exception;     /**     * 查找所有,并分页     *      * @param page 要返回的页数     * @param pageSize 没有记录数     * @return     */    ResponsePage<E> pageAll(String columns,Pagination pagination)throws Exception;     /**     * 保存对象     * @param e 对象     */    void save(E e)throws Exception;;     /**     * 删除对象     * @param e 对象     */    void delete(E e)throws Exception;;     /**     * 删除属性名为propertyName,属性值为value的记录     */    void deleteByProperty(String propertyName, Object value)throws Exception;     /**     * 通过属性查找并返回需要的列     * @param 需要返回的列名以“,”号隔开     * @param propertyName 属性名称     * @param value 属性的值     * @return     */    List<E> findByProperty(String columns,String propertyName, Object value)throws Exception;     /**     * 通过属性查找并返回所有列     * 不推荐使用全列查询除非必要(如:你当前无法知道有哪些列)     * @param 需要返回的列名以“,”号隔开     * @param propertyName 属性名称     * @param value 属性的值     * @return     */    @Deprecated    List<E> findByProperty(String propertyName, Object value)throws Exception;        /**     * 通过多个属性查找并指定的所有列     * @param columns 需要返回的列名     * @param propertyNames 属性名称数组     * @param values 属性值数组     * @return     */    List<E> findByPropertys(String columns,String[] propertyNames, Object[] values)throws Exception;            /**     * 通过多个属性查找并返回所有列     * 不推荐使用全列查询除非必要(如:你当前无法知道有哪些列)     * @param propertyNames 属性名称数组     * @param values 属性值数组     * @return     */    @Deprecated    List<E> findByPropertys(String[] propertyNames, Object[] values)throws Exception;        /**     * 通过属性模糊查找并指定的所有列     * @param columns 需要返回的列名     * @param propertyName 属性名称     * @param value 属性的值     * @return     */    List<E> findByPropertyFuzzy(String columns,String propertyName, Object value)throws Exception;        /**     * 通过属性模糊查找并返回所有列     * 不推荐使用全列查询除非必要(如:你当前无法知道有哪些列)     * @param propertyName 属性名称     * @param value 属性的值     * @return     */    @Deprecated    List<E> findByPropertyFuzzy(String propertyName, Object value)throws Exception;     /**     * 通过多个属性模糊查找并返回指定的列     * @param columns 需要返回的列名     * @param propertyNames 属性名称数组     * @param values 属性值数组     * @return     */    List<E> findByPropertysFuzzy(String columns,String[] propertyNames, Object[] values)throws Exception;        /**     * 通过多个属性模糊查找并返回所有列     * 不推荐使用全列查询除非必要(如:你当前无法知道有哪些列)     * @param propertyNames 属性名称数组     * @param values 属性值数组     * @return     */    @Deprecated    List<E> findByPropertysFuzzy(String[] propertyNames, Object[] values)throws Exception;            /**     * 通过多个属性查找,并分页, 属性名称数组和属性值数组的序列要对应     * @param columns 需要返回的列名     * @param propertyNames 属性名称数组     * @param values 属性值数组     * @param pagination 分页参数     * @return 分页后的结果     */    ResponsePage<E> pageByPropertys(String columns,String[] propertyNames, Object[] values,Pagination pagination)throws Exception;     /**     * 通过属性查找,并分页, 属性名称数组和属性值数组的序列要对应     * @param columns 需要返回的列名     * @param propertyNames 属性名称     * @param values 属性值     * @param pagination 分页参数     * @return     */    ResponsePage<E> pageByProperty(String columns,String propertyName, Object value,Pagination pagination)throws Exception;    /**     * 通过多个属性模糊查找,并分页, 属性名称数组和属性值数组的序列要对应     * @param columns 需要返回的列名     * @param propertyNames 属性名称数组     * @param values 属性值数组     * @param pagination 分页参数     * @return 分页后的结果     */    ResponsePage<E> pageByPropertysFuzzy(String columns,String[] propertyNames, Object[] values,Pagination pagination)throws Exception;     /**     * 通过属性模糊查找,并分页, 属性名称数组和属性值数组的序列要对应     * @param columns 需要返回的列名     * @param propertyNames 属性名称     * @param values 属性值     * @param pagination 分页参数     * @return     */    ResponsePage<E> pageByPropertyFuzzy(String columns,String propertyName, Object value,Pagination pagination)throws Exception;            List<E> queryBySQL(SqlBean sql)throws Exception;        List<Map<String, Object>> queryMapByHQL(String hql,Object[] args)throws Exception;        ResponsePage<E> pageBySQL(SqlBean sql,Pagination pagination)throws Exception;        ResponsePage<Map<String, Object>> pageMapByHQL(String hql,Object[] args,Pagination pagination)throws Exception;             /**     * 统计所有记录的总数     *      * @return 总数     */    int countAll()throws Exception;     /**     * 统计数据库中当propertyName=value时的记录总数     *      * @param propertyName     * @param value     * @return     */    int countByProperty(String propertyName, Object value)throws Exception;     /**     * 统计数据库中当多个propertyName=value时的记录总数     *      * @param propertyNames     * @param values     * @return     */    int countByPropertys(String[] propertyNames, Object[] values)throws Exception;         /**     * 统计数据库中当propertyName=value 模糊查询时的记录总数     *      * @param propertyName     * @param value     * @return     */    int countByPropertyFuzzy(String propertyName, Object value)throws Exception;     /**     * 统计数据库中当多个propertyName=value 模糊查询时的记录总数     *      * @param propertyNames     * @param values     * @return     */    int countByPropertysFuzzy(String[] propertyNames, Object[] values)throws Exception;            /**     * 根据SQL语句查询结果集条数     * @return     */    int countBySql(SqlBean sql)throws Exception;        /**     * 保存或更新     * @param e     */    void saveOrUpdate(E e)throws Exception;                 /**     * 通过ID查询对象     * @param id 主键编号     * @return     */    E findById(PK id)throws Exception;     /**     * 更新对象     * @param e     * @throws Exception      */    void update(E e) throws Exception;     /**     * 获得持久化对象的类型     *      * @return     */    Class<E> getClazz()throws Exception;         }


package com.sys.core.base.service;import java.io.Serializable;import java.util.List;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.sys.core.Pagination;import com.sys.core.SqlBean;import com.sys.core.base.dao.IBaseDao;import com.sys.core.response.ResponsePage;/** * 基础的Service抽象类,默认实现基础操作 *  * @date:2016年5月30日 * @param <E> * @param <PK> */@Service@Transactionalpublic  abstract class AbstractBaseService<E, PK extends Serializable>{@Autowiredprotected IBaseDao<E, PK> baseDao;public AbstractBaseService() {}public List<E> findAll() throws Exception {return baseDao.findAll("", null);}public List<E> findAll(String columns) throws Exception {return baseDao.findAll(columns, null);}public ResponsePage<E> pageAll(String columns, Pagination pagination) throws Exception {ResponsePage<E> responsePage = new ResponsePage<E>();responsePage.setRows(baseDao.findAll(columns, pagination));pagination.setDataSize(baseDao.countAll());responsePage.setPagination(pagination);return responsePage;}public void save(E e) throws Exception {baseDao.save(e);}public void delete(E e) throws Exception {baseDao.delete(e);}public void deleteByProperty(String propertyName, Object value) throws Exception {baseDao.deleteByProperty(propertyName, value);}public List<E> findByProperty(String columns, String propertyName, Object value) throws Exception {return baseDao.findByProperty(columns, propertyName, value, null);}public List<E> findByProperty(String propertyName, Object value) throws Exception {return baseDao.findByProperty("", propertyName, value, null);}public List<E> findByPropertys(String columns, String[] propertyNames, Object[] values) throws Exception {return baseDao.findByPropertys(columns, propertyNames, values, null);}public List<E> findByPropertys(String[] propertyNames, Object[] values) throws Exception {return baseDao.findByPropertys("", propertyNames, values, null);}public List<E> findByPropertyFuzzy(String columns, String propertyName, Object value) throws Exception {return baseDao.findByPropertyFuzzy(columns, propertyName, value, null);}public List<E> findByPropertyFuzzy(String propertyName, Object value) throws Exception {return baseDao.findByPropertyFuzzy("", propertyName, value, null);}public List<E> findByPropertysFuzzy(String columns, String[] propertyNames, Object[] values) throws Exception {return baseDao.findByPropertysFuzzy(columns, propertyNames, values, null);}public List<E> findByPropertysFuzzy(String[] propertyNames, Object[] values) throws Exception {return baseDao.findByPropertysFuzzy("", propertyNames, values, null);}public ResponsePage<E> pageByPropertys(String columns, String[] propertyNames, Object[] values, Pagination pagination) throws Exception {ResponsePage<E> responsePage = new ResponsePage<E>();pagination.setDataSize(baseDao.countByPropertys(propertyNames, values));responsePage.setRows(baseDao.findByPropertys(columns, propertyNames, values, pagination));responsePage.setPagination(pagination);return responsePage;}public ResponsePage<E> pageByProperty(String columns, String propertyName, Object value, Pagination pagination) throws Exception {ResponsePage<E> responsePage = new ResponsePage<E>();String[] propertyNames = { propertyName };Object[] values = { value };pagination.setDataSize(baseDao.countByPropertys(propertyNames, values));responsePage.setRows(baseDao.findByProperty(columns, propertyName, value, pagination));responsePage.setPagination(pagination);return responsePage;}public ResponsePage<E> pageByPropertysFuzzy(String columns, String[] propertyNames, Object[] values, Pagination pagination)throws Exception {ResponsePage<E> responsePage = new ResponsePage<E>();pagination.setDataSize(baseDao.countByPropertysFuzzy(propertyNames, values));responsePage.setRows(baseDao.findByPropertysFuzzy(columns, propertyNames, values, pagination));responsePage.setPagination(pagination);return responsePage;}public ResponsePage<E> pageByPropertyFuzzy(String columns, String propertyName, Object value, Pagination pagination) throws Exception {String[] propertyNames = { propertyName };Object[] values = { value };return pageByPropertysFuzzy(columns, propertyNames, values, pagination);}public List<E> queryBySQL(SqlBean sql) throws Exception {return baseDao.queryBySQL(sql);}public List<Map<String, Object>> queryMapByHQL(String hql, Object[] args) throws Exception {return baseDao.queryMapByHQL(hql, args, null);}public ResponsePage<E> pageBySQL(SqlBean sql, Pagination pagination) throws Exception {ResponsePage<E> responsePage = new ResponsePage<E>();pagination.setDataSize(baseDao.queryCountBySQL(sql));responsePage.setRows(baseDao.queryBySQL(sql, pagination));responsePage.setPagination(pagination);return responsePage;}public ResponsePage<Map<String, Object>> pageMapByHQL(String hql, Object[] args, Pagination pagination) throws Exception {ResponsePage<Map<String, Object>> responsePage = new ResponsePage<Map<String, Object>>();pagination.setDataSize(baseDao.mapCountByHQL(hql, args));responsePage.setRows(baseDao.queryMapByHQL(hql, args, pagination));responsePage.setPagination(pagination);return responsePage;}public int countAll() throws Exception {return baseDao.countAll();}public int countByProperty(String propertyName, Object value) throws Exception {String[] propertyNames = { propertyName };Object[] values = { value };return baseDao.countByPropertys(propertyNames, values);}public int countByPropertys(String[] propertyNames, Object[] values) throws Exception {return baseDao.countByPropertys(propertyNames, values);}public int countByPropertyFuzzy(String propertyName, Object value) throws Exception {String[] propertyNames = { propertyName };Object[] values = { value };return baseDao.countByPropertysFuzzy(propertyNames, values);}public int countByPropertysFuzzy(String[] propertyNames, Object[] values) throws Exception {return baseDao.countByPropertysFuzzy(propertyNames, values);}public int countBySql(SqlBean sql) throws Exception {return baseDao.queryCountBySQL(sql);}public void saveOrUpdate(E e) throws Exception {baseDao.saveOrUpdate(e);}public E findById(PK id) throws Exception {return baseDao.findById(id);}public void update(E e) throws Exception {baseDao.update(e);}public Class<E> getClazz() throws Exception {return baseDao.getClazz();}}



0 0
原创粉丝点击