一个泛型Hibernate DAO实现

HibernateDaoSupport二次封装组件,快速统计和查询,修改 HibernateDaoSupport二次封装组件,快速统计和查询,修改,删除,并且对SQL语句的in,or,exitsts都有涉及 立即下载
自己四处参考,写写抄抄折腾出来的一个泛型Hibernate DAO,用了Spring的HibernateDaoSupport。提供基本的CRUD操作,支持分页查询,可使用HQL、Criteria和DetachedCriteria。
废话不说了,上代码

package sgf4web.dao;

import java.io.Serializable;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.*;
import org.hibernate.criterion.*;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import sgf4web.dao.support.PaginationSupport;
import sgf4web.util.GenericsUtils;

/**
 * 泛型Hibernate DAO类
 * 
 * 
@author DigitalSonic
 
*/

@SuppressWarnings(
"unchecked")
public class HibernateGenericDao<T, ID extends Serializable> extends HibernateDaoSupport {
    
private Class<T> pojoClass;
    
    
/**
     * 初始化DAO,获取POJO类型
     
*/

    
public HibernateGenericDao() {
//        this.pojoClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        this.pojoClass = GenericsUtils.getSuperClassGenricType(getClass());
    }

    
    
/**
     * 获得该DAO对应的POJO类型
     
*/

    
public Class<T> getPojoClass() {
        
return this.pojoClass;
    }

    
    
/**
     * 获得该DAO对应的POJO类型名
     
*/

    
public String getPojoClassName() {
        
return getPojoClass().getName();
    }


    
//加载对象
    
    
/**
     * 加载所有的对象
     
*/

    
public List<T> loadAll() {
        
return (List<T>)getHibernateTemplate().loadAll(getPojoClass());
    }

    
    
/**
     * 根据hql查询
     *
     * 
@param values 可变参数
     
*/

    
public List find(String hql, Object... values) {
        
return getHibernateTemplate().find(hql, values);
    }


    
/**
     * 根据条件加载对象
     * 
     * 
@param criteria Criteria实例
     
*/

    
public List<T> findByCriteria(final Criteria criteria) {
        List list 
= criteria.list(); 
        
return transformResults(list);
    }

    
    
/**
     * 根据条件加载对象
     * 
@param detachedCriteria DetachedCriteria实例
     
*/

    
public List<T> findByCriteria(final DetachedCriteria detachedCriteria) {
        
return (List<T>) getHibernateTemplate().execute(new HibernateCallback() {
               
public Object doInHibernate(Session session) throws HibernateException {
                   Criteria criteria 
= detachedCriteria.getExecutableCriteria(session);
                   List list 
= criteria.list(); 
                   
return transformResults(list); 
               }

           }
, true);
    }

    
    
/**
     * 根据给定的实例查找对象
     
*/

    
public List<T> findByExample(T instance) {
        List
<T> results = (List<T>)getHibernateTemplate().findByExample(instance);
        
return results;
    }
    
    
    
/**
     * 根据ID查找对象
     
*/

    
public T findById(ID id) {
        
return (T) getHibernateTemplate().get(getPojoClassName(), id);
    }

    
    
/**
     * 根据某个具体属性进行查找
     
*/

    
public List<T> findByProperty(String propertyName, Object value) {
       String queryString 
= "from " + getPojoClassName() + " as model where model." 
                               
+ propertyName + "= ?";
       
return (List<T>)getHibernateTemplate().find(queryString, value);
    }

    
    
//新建、修改、删除
    
    
/**
     * 新建对象实例化
     
*/

    
public ID save(T transientInstance) {
        
return (ID)getHibernateTemplate().save(transientInstance);
    }

    
    
/**
     * 更新已存在的对象
     
*/

    
public void update(T transientInstance) {
        getHibernateTemplate().update(transientInstance);
    }

    
    
/**
     * 删除指定ID的对象
     
*/

    
public void delete(ID id) {
           T instance 
= findById(id);
           
if (instance != null)
               getHibernateTemplate().delete(instance);
    }

    
    
/**
     * 删除指定对象
     
*/

    
public void delete(T persistentInstance) {
        getHibernateTemplate().delete(persistentInstance);
    }
    
    
    
//分页
    /**
     * 根据Criteria加载分页,指定页大小和起始位置
     
*/

    
public PaginationSupport findPageByCriteria(final Criteria criteria, final int pageSize, final int startIndex) {   
        
int totalCount = getCountByCriteria(criteria);   
        criteria.setProjection(
null);
        List items 
= criteria.setFirstResult(startIndex).setMaxResults(pageSize).list();
        items 
= transformResults(items);
        PaginationSupport ps 
= new PaginationSupport(items, totalCount, pageSize, startIndex);
        
return ps;
    }

    
    
/**
     * 根据Criteria加载分页,默认页大小,从第0条开始
     
*/

    
public PaginationSupport findPageByCriteria(final Criteria criteria) {   
        
return findPageByCriteria(criteria, PaginationSupport.PAGESIZE, 0);   
    }
   
 
    
/**
     * 根据Criteria加载分页,默认页大小,从第startIndex条开始
     
*/

    
public PaginationSupport findPageByCriteria(final Criteria criteria, final int startIndex) {   
        
return findPageByCriteria(criteria, PaginationSupport.PAGESIZE, startIndex);   
    }

    
    
/**
     * 根据Criteria统计总数
     
*/

    
public int getCountByCriteria(final Criteria criteria) {   
        Integer count 
= (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();    
        
return count.intValue();   
    }

    
    
/**
     * 根据DetachedCriteria加载分页,指定页大小和起始位置
     
*/

    
public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria, final int pageSize, final int startIndex) {   
        
return (PaginationSupport) getHibernateTemplate().execute(new HibernateCallback() {   
            
public Object doInHibernate(Session session) throws HibernateException {   
                Criteria criteria 
= detachedCriteria.getExecutableCriteria(session);
                
int totalCount = ((Integer) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();   
                criteria.setProjection(
null);
                List items 
= criteria.setFirstResult(startIndex).setMaxResults(pageSize).list();
                items 
= transformResults(items);
                PaginationSupport ps 
= new PaginationSupport(items, totalCount, pageSize, startIndex);   
                
return ps;   
            }

        }
, true);   
    }

    
    
/**
     * 根据DetachedCriteria加载分页,默认页大小,从第0条开始
     
*/

    
public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria) {   
        
return findPageByCriteria(detachedCriteria, PaginationSupport.PAGESIZE, 0);   
    }
   
  
    
/**
     * 根据DetachedCriteria加载分页,默认页大小,从第startIndex条开始
     
*/

    
public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria, final int startIndex) {   
        
return findPageByCriteria(detachedCriteria, PaginationSupport.PAGESIZE, startIndex);   
    }
 
    
    
/**
     * 根据DetachedCriteria统计总数
     
*/

    
public int getCountByCriteria(final DetachedCriteria detachedCriteria) {   
        Integer count 
= (Integer) getHibernateTemplate().execute(new HibernateCallback() {   
            
public Object doInHibernate(Session session) throws HibernateException {   
                Criteria criteria 
= detachedCriteria.getExecutableCriteria(session);   
                
return criteria.setProjection(Projections.rowCount()).uniqueResult();   
            }
   
        }
, true);   
        
return count.intValue();   
    }
 
    
    
/**
     * 根据hql加载分页,指定页大小和起始位置
     
*/

    
public PaginationSupport findPageByQuery(final String hql, final int pageSize, final int startIndex, Object...values) {
        
int totalCount = getCountByQuery(hql, values);
        
        
if (totalCount < 1)
            
return new PaginationSupport(new ArrayList(0), 0);

        Query query 
= createQuery(hql, values);
        List items 
= query.setFirstResult(startIndex).setMaxResults(pageSize).list();
        PaginationSupport ps 
= new PaginationSupport(items, totalCount, pageSize, startIndex);
        
return ps;
    }

    
    
/**
     * 根据hql加载分页,默认页大小,从第0条开始
     
*/

    
public PaginationSupport findPageByQuery(final String hql, Object...values) {   
        
return findPageByQuery(hql, PaginationSupport.PAGESIZE, 0, values);   
    }
   
 
    
/**
     * 根据hql加载分页,默认页大小,从第startIndex条开始
     
*/

    
public PaginationSupport findPageByQuery(final String hql, final int startIndex, Object...values) {   
        
return findPageByQuery(hql, PaginationSupport.PAGESIZE, startIndex, values);  
    }

    
    
/**
     * 根据hql统计总数
     
*/

    
public int getCountByQuery(final String hql, Object...values) {   
        String countQueryString 
= " select count (*) " + removeSelect(removeOrders(hql));
        List countlist 
= getHibernateTemplate().find(countQueryString, values);
        
return (Integer) countlist.get(0);
    }

    
    
//创建Criteria和Query
    
    
/**
     * 创建Criteria对象
     *
     * 
@param criterions 可变的Restrictions条件列表
     
*/

    
public Criteria createCriteria(Criterion...criterions) {
        Criteria criteria 
= getSession().createCriteria(getPojoClass());
        
for (Criterion c : criterions)
            criteria.add(c);
        
return criteria;
    }


    
/**
     * 创建Criteria对象,带排序字段与升降序字段
     
*/

    
public Criteria createCriteria(String orderBy, boolean isAsc, Criterion...criterions) {
        Criteria criteria 
= createCriteria(criterions);
        
if (isAsc)
            criteria.addOrder(Order.asc(orderBy));
        
else
            criteria.addOrder(Order.desc(orderBy));
        
return criteria;
    }

    
    
/**
     * 方法取自SpringSide.
     * 创建Query对象. 对于需要first,max,fetchsize,cache,cacheRegion等诸多设置的函数,可以在返回Query后自行设置.
     * 留意可以连续设置,如下:
     * <pre>
     * dao.getQuery(hql).setMaxResult(100).setCacheable(true).list();
     * </pre>
     * 调用方式如下:
     * <pre>
     *        dao.createQuery(hql)
     *        dao.createQuery(hql,arg0);
     *        dao.createQuery(hql,arg0,arg1);
     *        dao.createQuery(hql,new Object[arg0,arg1,arg2])
     * </pre>
     *
     * 
@param values 可变参数.
     
*/

    
public Query createQuery(String hql, Object... values) {
        Query query 
= getSession().createQuery(hql);
        
for (int i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }

        
return query;
    }

    
    
/**
     * 方法取自SpringSide.
     * 去除hql的select子句,未考虑union的情况
     
*/

    
private static String removeSelect(String hql) {
        
int beginPos = hql.toLowerCase().indexOf("from");
        
return hql.substring(beginPos);
    }


    
/**
     * 方法取自SpringSide.
     * 去除hql的orderby子句
     
*/

    
private static String removeOrders(String hql) {
        Pattern p 
= Pattern.compile("order/s*by[/w|/W|/s|/S]*", Pattern.CASE_INSENSITIVE);
        Matcher m 
= p.matcher(hql);
        StringBuffer sb 
= new StringBuffer();
        
while (m.find()) {
            m.appendReplacement(sb, 
"");
        }

        m.appendTail(sb);
        
return sb.toString();
    }

    
    
/**
     * 将联合查询的结果内容从Map或者Object[]转换为实体类型,如果没有转换必要则直接返回
     
*/

    
private List transformResults(List items) {
        
if (items.size() > 0) {
            
if (items.get(0) instanceof Map) {
                ArrayList list 
= new ArrayList(items.size());
                
for (int i = 0; i < items.size(); i++) {
                    Map map 
= (Map)items.get(i);
                    list.add(map.get(CriteriaSpecification.ROOT_ALIAS));
                }

                
return list;
            }
 else if (items.get(0) instanceof Object[]) {
                ArrayList list 
= new ArrayList(items.size());
                
int pos = 0;
                
for (int i = 0; i < ((Object[])items.get(0)).length; i++) {
                    
if (((Object[])items.get(0))[i].getClass() == getPojoClass()) {
                        pos 
= i;
                        
break;
                    }

                }

                
for (int i = 0; i < items.size(); i++) {
                    list.add(((Object[])items.get(i))[pos]);
                }

                
return list;
            }
 else
                
return items;
        }
 else
            
return items;
    }

}

package sgf4web.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 泛型参数辅助类
 * 
 * 
@author DigitalSonic
 
*/

@SuppressWarnings(
"unchecked")
public class GenericsUtils {
    
/**
     * 通过反射,获得定义Class时声明的父类的第一个范型参数的类型。
     
*/

    
public static Class getSuperClassGenricType(Class clazz) {
        
return getSuperClassGenricType(clazz, 0);
    }

    
    
/**
     * 通过反射,获得定义Class时声明的父类的范型参数的类型。
     * 如没有找到符合要求的范型参数,则递归向上直到Object。
     *
     * 
@param clazz 要进行查询的类
     * 
@param index 如有多个范型声明该索引从0开始
     * 
@return 在index位置的范型参数的类型,如果无法判断则返回<code>Object.class</code>
     
*/

    
public static Class getSuperClassGenricType(Class clazz, int index) {
        
boolean flag = true;
        Type genType 
= clazz.getGenericSuperclass();
        Type[] params 
= null;
        
        
if (!(genType instanceof ParameterizedType))
            flag 
= false;
        
else {
            params 
= ((ParameterizedType) genType).getActualTypeArguments();
            
if (index >= params.length || index < 0)
                flag 
= false;
            
if (!(params[index] instanceof Class))
                flag 
= false;
        }

        
if (!flag) {
            clazz 
= clazz.getSuperclass();
            
if (clazz == Object.class)
                
return Object.class;
            
else
                
return getSuperClassGenricType(clazz, index);
        }

        
        
return (Class) params[index];
    }

}



package sgf4web.dao.support;

import java.util.List;

/**
 * 分页类,参考自JavaEye及SpringSide
 
*/

@SuppressWarnings(
"unchecked")
public class PaginationSupport {
    
public final static int PAGESIZE = 10;

    
private int pageSize = PAGESIZE;

    
private List items;

    
private int totalCount;

    
private int[] indexes = new int[0];

    
private int startIndex = 0;

    
public PaginationSupport(List items, int totalCount) {
        setPageSize(PAGESIZE);
        setTotalCount(totalCount);
        setItems(items);
        setStartIndex(
0);
    }


    
public PaginationSupport(List items, int totalCount, int startIndex) {
        setPageSize(PAGESIZE);
        setTotalCount(totalCount);
        setItems(items);
        setStartIndex(startIndex);
    }


    
public PaginationSupport(List items, int totalCount, int pageSize, int startIndex) {
        setPageSize(pageSize);
        setTotalCount(totalCount);
        setItems(items);
        setStartIndex(startIndex);
    }


    
/**
     * 将页码转换为列表的startIndex,页大小为默认大小
     
*/

    
public static int convertFromPageToStartIndex(int pageNo) {
        
return (pageNo - 1) * PAGESIZE;
    }

    
    
/**
     * 将页码转换为列表的startIndex
     
*/

    
public static int convertFromPageToStartIndex(int pageNo, int pageSize) {
        
return (pageNo - 1) * pageSize;
    }


    
public List getItems() {
        
return items;
    }


    
public void setItems(List items) {
        
this.items = items;
    }


    
public int getPageSize() {
        
return pageSize;
    }


    
public void setPageSize(int pageSize) {
        
this.pageSize = pageSize;
    }


    
public int getTotalCount() {
        
return totalCount;
    }


    
/**
     * 设置数据总数,并计算各页起始位置
     
*/

    
public void setTotalCount(int totalCount) {
        
if (totalCount > 0) {
            
this.totalCount = totalCount;
            
int count = totalCount / pageSize;
            
if (totalCount % pageSize > 0)
                count
++;
            indexes 
= new int[count];
            
for (int i = 0; i < count; i++) {
                indexes[i] 
= pageSize * i;
            }

        }
 else {
            
this.totalCount = 0;
        }

    }


    
public int[] getIndexes() {
        
return indexes;
    }


    
public void setIndexes(int[] indexes) {
        
this.indexes = indexes;
    }


    
public int getStartIndex() {
        
return startIndex;
    }


    
/**
     * 设置当前起始位置
     
*/

    
public void setStartIndex(int startIndex) {
        
if (totalCount <= 0)
            
this.startIndex = 0;
        
else if (startIndex >= totalCount)
            
this.startIndex = indexes[indexes.length - 1];
        
else if (startIndex < 0)
            
this.startIndex = 0;
        
else {
            
this.startIndex = indexes[startIndex / pageSize];
        }

    }


    
/**
     * 获得下页起始位置
     
*/

    
public int getNextIndex() {
        
int nextIndex = getStartIndex() + pageSize;
        
if (nextIndex >= totalCount)
            
return getStartIndex();
        
else
            
return nextIndex;
    }


    
/**
     * 获得上页起始位置
     
*/

    
public int getPreviousIndex() {
        
int previousIndex = getStartIndex() - pageSize;
        
if (previousIndex < 0)
            
return 0;
        
else
            
return previousIndex;
    }


    
/**
     * 取总页数.
     
*/

    
public long getTotalPageCount() {
        
if (totalCount % pageSize == 0)
            
return totalCount / pageSize;
        
else
            
return totalCount / pageSize + 1;
    }


    
/**
     * 取该页当前页码,页码从1开始.
     
*/

    
public long getCurrentPageNo() {
        
return startIndex / pageSize + 1;
    }


    
/**
     * 该页是否有下一页.
     
*/

    
public boolean hasNextPage() {
        
return this.getCurrentPageNo() < this.getTotalPageCount() - 1;
    }


    
/**
     * 该页是否有上一页.
     
*/

    
public boolean hasPreviousPage() {
        
return this.getCurrentPageNo() > 1;
    }

}
ZYNQ实战:手把手教你用AXI4-Full IP核打通PL与PS的DDR数据通道 本文提供了一份详细的ZYNQ实战指南,手把手教你创建并使用具备AXI4-Full Master接口的自定义IP核,实现PL(可编程逻辑)通过AXI HP接口直接读写PS(处理系统)的DDR内存。文章涵盖了从Vivado硬件设计、IP核配置、地址映射到Vitis软件验证的完整流程,并深入解析了数据一致性(禁用Cache)等关键要点,旨在帮助开发者掌握ZYNQ异构计算中高效数据搬运的核心技术。 阅读详情

相关推荐

如何使用ArcGIS Pro制作带基底三维地图

点击运行生成范围线,因为之前对高程进行了夸大,导致生成的范围线和地形边缘不重合,我们打开范围线的图层属性,选择高程选项卡,要素位于选择地面上,如下图所示。目前制作的三维地图下面是空的一片,现在添加一个基底,在工具箱内点击“3D Analyst工具\栅格\转换\栅格范围”,调用栅格范围工具,如下图所示。打开ArcGIS Pro,新建一个局部场景,在高程表面下,地面上点击右键,选择添加高程源图层,将需要制作三维地图的DEM数据加载进来,如下图所示。在要素图层菜单内,类型选择绝对高度,如下图所示。

3978

Hibernate 查询数据库有数据,但hibernate返回null

1:Hibernate 查询异常 ssh查询无数据不会报错,有数据控制台无报错,dubug进去报空指针, 如图: sql语句可以查出数据但是java数据中有的为null sql语句直接在数据库查询有结果,在程序中无报错不展示,耗费了时间,最终解决, 修改数据库字段id字段,赋值后解决,程序查询出结果, 原因:Hibernate 查询配置了某些字段不能为空,为空则异常 参考 https://blog.youkuaiyun.com/fireofjava/article/details/23757657 ...

kang1011的博客 2731

利用Solidworks2020将挖掘机装配体转换为URDF模型

利用Solidworks2020将挖掘机装配体转换为URDF模型一、下载sw_urdf_exporter插件 URDF(Universal Robot Description Format)——通用机器人描述格式,它是ROS里边使用的一种机器人的描述文件,包含的内容有:连杆、关节,运动学和动力学参数、可视化模型、碰撞检测模型等。 一、下载sw_urdf_exporter插件 ROS提供了SolidWorks转URDF的插件(下载链接)—sw2urdfSetup.exe,下载后点击安装,安装完成后就能在sol

weixin_48192326的博客 6101

[Hibernate] - Generic Dao

使用泛型写了一个通用的Hibernate DAO类。 GenericDao接口 package com.my.dao; import java.io.Serializable; import java.util.List; /** * Generic DAO interface * @author Robin * * @param <...

weixin_30565327的博客 148

京东联盟API实战:5分钟搞定商品返利链接生成(附Python代码)

本文详细介绍了如何利用京东联盟API快速构建自动化商品返利链接生成系统。通过Python代码实战,从API申请、环境配置到核心功能封装,手把手教你实现批量商品信息查询与推广链接生成,帮助内容创作者和开发者大幅提升电商推广效率。

weixin_29216957的博客 673

抖音X-Medusa风控逆向:unidbg环境重建与魔改AES还原

X-Medusa并非传统加密算法,而是深度耦合运行时环境的动态混淆系统,其核心是硬件指纹感知、线程上下文绑定与非标AES变异。理解其原理需跳出‘找密钥’思维,转向对CPU型号、系统属性、微秒级时间及内存布局的综合建模。技术价值在于将不可控的客户端风控,转化为可复现、可配置、可运维的服务化能力;典型应用场景包括合规数据采集、API协议适配与移动安全研究。本文聚焦Android native层逆向实践,基于unidbg实现高保真环境模拟,并完整还原S-Box动态生成、MixColumns矩阵变异与轮密钥XOR扰

weixin_33783283的博客 685

HibernateDao层逻辑

package com.idoo.iosms.core.hibernate.hibernate; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUti

okkeqin的专栏 1932

OPTI Toolbox v2.28 安装与 3 个求解器补全:SCIP、SeDuMi、MOSEK 配置详解

本文详细介绍了OPTI Toolbox v2.28在MATLAB环境下的完整安装指南,包括SCIP、SeDuMi和MOSEK三个关键求解器的配置与优化技巧。通过分步指导和实战案例,帮助用户高效搭建强大的优化工具包,提升混合整数规划、二次约束二次规划等复杂问题的求解效率。

weixin_29039773的博客 350

Hibernate分页查询

通常使用的Hibernate通常是三种:hql查询,QBC查询和QBE查询:1、QBE(Qurey By Example)检索方式QBE是最简单的,但是功能也是最弱的,QBE的功能不是特别强大,仅在某些场合下有用。一个典型的使用场合就是在查询窗口中让用户输入一系列的查询条件,然后返回匹配的对象。QBE只支持=和like比较运算符,无法不大区间值,及其或的匹配。在这种情况下,还是采用HQL检索方...

thewebcode 225

基于Python的网贷平台数据爬虫实战:Scrapy+Selenium+反反爬策略

python复制下载# items.py本文详细介绍了如何使用Python构建一个完整的网贷平台数据爬虫系统,涵盖了从基础爬取到高级反反爬策略的全套解决方案。我们使用了Scrapy框架作为基础,结合Selenium处理动态内容,实现了多种反反爬策略,并探讨了分布式爬虫的实现方式。机器学习识别验证码基于深度学习的网页结构变化检测自动化行为模拟的更精细控制基于Kubernetes的弹性爬虫集群。

2201_76125261的博客 1560

GPU服务器维修全流程:从检测到解锁

《GPU服务器维修维保全流程指南》摘要:本文系统介绍GPU服务器从检测到解锁的完整维修流程。检测环节包含物理检查(氧化层、散热、PCB板)和电子诊断(ECC报错率、电源波动等);核心维修技术涵盖PCB板修复(微孔镀铜、BGA返修)和芯片级维修(成功率78-92%);解锁验证阶段包括性能解锁(VBIOS重写)和72小时稳定性测试。文末提供故障速查表及维保建议,强调定期除尘可降低38%故障率,推荐环境粉尘浓度控制在≤0.3mg/m³。

2401_89353317的博客 890

dao层用Hibernate 查询 返回null无值、并且控制台没有输出SQL日志,也没有报任何异常

最近搭建了一个SpringMVC3.2+Hibernate+JDBC+Spring security3.2 的项目,全注解模式,遇到一个很二的问题。  问题现象是:1. 登陆时验证用户时,查询不到对应的User,返回null,但数据库里肯定是有这个User的。 2.控制台也没有输出Hibernate相关SQL日志 通过Debug 看,发现返回User确实是Null啊。         关键

JimBo3693的专栏 3038

PCL点云DBSCAN聚类算法:基于密度的点云聚类

核心点是在给定半径内拥有足够多邻居点的点,边界点是在给定半径内没有足够多邻居点但是位于核心点的邻域内的点,噪声点是既不是核心点也不是边界点的点。本文将介绍PCL中的DBSCAN(基于密度的空间聚类应用噪声)算法,用于点云数据的聚类。上述示例代码首先从PCD文件中读取点云数据,并设置了DBSCAN聚类的参数,包括邻域搜索半径(epsilon)和邻域内最小点数(min_points)。需要注意的是,示例代码中的点云数据格式为pcl::PointXYZ,如果使用其他类型的点云数据,需要相应地修改代码。

LpmShell的博客 1238

[转]一个泛型Hibernate DAO实现

java 代码 package sgf4web.dao;       import java.io.Serializable;    import java.util.*;    import java.util.regex.Matcher;    import java.util.regex.Pattern;       im...

feigme H.Guo的专栏 146

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

一个简单的Hibernate泛型Dao的实现 ---- 20160624

项目中用到的简单的泛型Dao的实现。Mark一下,以后可以适当修改以后直接使用。

Simon_9527的博客 194

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

泛型 DAO 的基础CRUD

对于大多数开发人员,为系统中的每个 DAO 编写几乎相同的代码到目前为止已经成为一种习惯。虽然所有人都将这种重复标识为 “代码味道”,但我们大多数都已经学会忍受它。其实有解决方案。可以使用许多 ORM 工具来避免代码重复。例如,使用 Hibernate,您可以简单地为所有的持久域对象直接使用会话操作。这种方法的缺点是损失了类型安全。 为什么您要为数据访问代码提供类型安全接口?我会争辩说,当它

Kei's Blog 1918

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

JPA的泛型DAO设计及使用

使用如Hibernate或者JPA作为持久化的解决方案时,设计一个泛型的DAO抽象父类可以方便各个实体的通用CRUD操作。由于此时大部分实体DAO的CRUD操作基本一样,采用泛型设计解决这个问题,带来了简洁代码的好处。 问题的关键在于我们需要在代码中获取抽象DAO父类(BaseEntityDAOImpl<T>)中的泛型信息。 由于Java的泛型是基于泛型擦除实现的,因...

banglaiqi4707的博客 821

泛型 Hibernate DAO 例

泛型 Hibernate DAO 例import java.io.Serializable;import java.util.List;public interface GenericDAO {  List findAll();  T persist(T entity);  void remove(T entity);}=========import java.io.Ser

飒龙的专栏 770

一个好用的hibernate泛型dao

以前从springside2.0上搞下来的很好用的,基本实现dao零编码只要配置xml文件就行了。 先看图: 一共4层,com.demonstration.hibernate.basedao是我加的用来进一步解耦hibernate和spring的耦合。 原来的官方解释如下: SpringSide对Hibernate做了三层封装: 第一层:HibernateGenericDao,基于s

Aries的专栏 996

开发积累—泛型工具类

前言:使用SSH2中使用的泛型工具类,以前写泛型比较麻烦。今天收集到一个工具类,好东呀!!分享给大家,绝对有用。JAVA版的web应用程序使用。

好刹那的专栏 2297

java 泛型 重构_对Java泛型的简单理解,并对Hibernate Dao重构

引用维基百科的定义:泛型的定义主要有以下两种:在程序编码中一些包含类型参数的类型,也就是说泛型的参数只可以代表类,不能代表个别对象。(这是当今较常见的定义)在程序编码中一些包含参数的类。其参数可以代表类或对象等等。(现在人们大多把这称作模板)泛型的好处是在编译的时候检查类型安全,并且所有的强制转换都是自动和隐式的,提高代码的重用率。泛型只不过是java中的类型而已,继承自Type接口。 泛型的意义...

weixin_30895059的博客 184

java 泛型的 设置值、取值

public abstract class DaoSupportImpl implements DaoSupport { @Resource private SessionFactory sessionFactory; private Class clazz; public DaoSupportImpl() { // 使用反射技术得到T的真实类型 ParameterizedTy

LzwGlory的专栏 8029

基于hibernate的泛型dao实现

我们在进行hibernate开发时,因为hibernate是基于对象的ORM,所以由此我们可以在hibernate的基础上在做一层封装,从而大大简化我们的DAO层代码。 首先封装一个分页工具类:Pager<T> public class Pager<T> { private int offset; private int pagesize; private L...

tonysong111073的专栏 279

不要重复DAO!使用Hibernate 和Spring AOP 构建泛型类型安全的DAO

对于大多数开发人员,为系统中的每个 DAO 编写几乎相同的代码到目前为止已经成为一种习惯。虽然所有人都将这种重复标识为 “代码味道”,但我们大多数都已经学会忍受它。其实有解决方案。可以使用许多 ORM 工具来避免代码重复。例如,使用 Hibernate,您可以简单地为所有的持久域对象直接使用会话操作。这种方法的缺点是损失了类型安全。 为什么您要为数据访问代码提供类型安全接口?我会争辩说,当它与现...

zhangziyangup 117
上一篇: 原来我也会写文档
下一篇: 一个泛型Hibernate DAO实现
dingx
博客等级 码龄24年 67粉丝 112原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值