• Hibernate Dao映射配置通用接口类反射获取加载calass实例


    接口:

    package com.ph.dao;

    import java.io.Serializable;
    import java.util.List;
    import org.hibernate.criterion.DetachedCriteria;
    public interface BaseDao<T> {
    public void save(T t);
    public void delete(T t);
    public void update(T t);
    public T findById(Serializable id);
    public List<T>  findAll();
    public Integer findCount(DetachedCriteria detachedCriteria);
    public List<T> findByPage(DetachedCriteria detachedCriteria,Integer begin,Integer pageSize);
    }

    接口实现类:

    package com.ph.dao.impl;
    import java.io.Serializable;
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    import java.util.List;
    import org.hibernate.criterion.DetachedCriteria;
    import org.hibernate.criterion.Projections;
    import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
    import com.ph.dao.BaseDao;
    public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {
    private Class clazz;
    public BaseDaoImpl() {
    //获取子类
    Class clazz = this.getClass();
    //反射加载父类,获取参数化类型
    Type type = clazz.getGenericSuperclass();
    //获取实际类型参数
    ParameterizedType pType = (ParameterizedType) type;
    Type[] types = pType.getActualTypeArguments();
    //设置clazz
    this.clazz = (Class) types[0];
    }
    public void save(T t) {
    this.getHibernateTemplate().save(t);
    }
    public void delete(T t) {
    this.getHibernateTemplate().delete(t);
    }
    public void update(T t) {
    this.getHibernateTemplate().update(t);
    }
    public T findById(Serializable id) {
    return (T) this.getHibernateTemplate().get(clazz, id);
    }
    public List<T>  findAll() {
    return (List<T>) this.getHibernateTemplate().find("from "+clazz.getSimpleName());
    }
    public Integer findCount(DetachedCriteria detachedCriteria) {
    detachedCriteria.setProjection(Projections.rowCount());
    List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(detachedCriteria);
    if (list.size()>0) {
    return list.get(0).intValue();
    }
    return 0;
    }
    public List<T> findByPage(DetachedCriteria detachedCriteria,Integer begin,Integer pageSize) {
    detachedCriteria.setProjection(null);
    return (List<T>) this.getHibernateTemplate().findByCriteria(detachedCriteria, begin, pageSize);
    }
    }
  • 相关阅读:
    vscode快捷键的中文版
    小程序css--view标签下英文不换行,中文会自动换行
    微信小程序设置背景铺满全屏
    MAC系统上不能调试华为手机
    js 空函数的作用
    五子棋 AI(AIpha-beta算法)
    ( function(){…} )()和( function (){…} () )是两种立即执行函数
    vscode快捷键
    20192328牛梓萌第一周作业
    第一次作业
  • 原文地址:https://www.cnblogs.com/hirampeng/p/9716318.html
Copyright © 2020-2023  润新知