博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于BaseDaoImpl的简单示例
阅读量:4097 次
发布时间:2019-05-25

本文共 7283 字,大约阅读时间需要 24 分钟。

          示例:实现basedao

package com.cn.base.dao.impl;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.util.ArrayList;import java.util.List;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import com.fang.base.dao.IBaseDao;import com.fang.util.HibernateSessionFactory;import com.fang.util.Page;public abstract class BaseDaoImpl
implements IBaseDao
{ private Log log = LogFactory.getLog(this.getClass()); private Class
entityClass; @SuppressWarnings("unchecked") public BaseDaoImpl() { //1、尝试基本的获取对象实体类对象方法 entityClass = (Class
) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; /*2、或尝试这个关于代理的如果有T的实例t,创建代理后的实例proxiedT,你拿到proxiedT 后怎么 才能拿到 t? 通过代理生成的类应该是继承了被代理的类,所以getGenericSuperclass只是取到被代理类的Type。 正常应该是要取到被代理类所继承的父类的Type, 所以要先getSuperclass取到被代理类再getGenericSuperclass取到父类的Type才成*/ /*Type type = getClass().getGenericSuperclass(); if(!(type instanceof ParameterizedType)){ type = getClass().getSuperclass().getGenericSuperclass(); } entityClass = (Class
)((ParameterizedType)type).getActualTypeArguments()[0];*/ } public Session getSession() { return HibernateSessionFactory.getSession(); } public void closeSession(){ HibernateSessionFactory.closeSession(); } @Override public void save(T instance) { log.debug("saving "+instance+" instance"); Transaction tx = getSession().beginTransaction(); try { getSession().save(instance); tx.commit(); log.debug("save successful"); } catch (RuntimeException re) { tx.rollback(); log.error("save failed", re); throw re; } finally{ closeSession(); } } @Override public void delete(T instance) { log.debug("deleting "+instance+" instance"); Transaction tx = getSession().beginTransaction(); try { getSession().delete(instance); tx.commit(); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } finally{ closeSession(); } } @Override public void update(T instance) { log.debug("updating "+instance+" instance"); Transaction tx = getSession().beginTransaction(); try { getSession().update(instance); tx.commit(); log.debug("update successful"); } catch (RuntimeException re) { tx.rollback(); log.error("update failed", re); throw re; } finally{ closeSession(); } } @SuppressWarnings("rawtypes") @Override public Object findById(Class clazz, Integer id) { log.debug("getting "+clazz+" instance with id: " + id); try { //Hibernate.initialize(District.class); Object o = getSession().get(clazz,id); return o; } catch (RuntimeException re) { log.error("get failed", re); throw re; } finally{ closeSession(); } } @SuppressWarnings("unchecked") @Override public List
findAll() { log.debug("getting "+entityClass+" List All "); try { String hql = "FROM "+entityClass; Query queryObject = getSession().createQuery(hql); return queryObject.list(); } catch (RuntimeException re) { log.error("find by HQL ", re); throw re; } finally{ closeSession(); } } /** * 根据class类查询数据 * @param class */ @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public List findAll(Class clazz) { log.debug("getting "+clazz+" List All "); try { String c = clazz.toString(); String hql = "FROM "+c.substring(c.lastIndexOf(".")+1,c.length()); Query queryObject = getSession().createQuery(hql); return queryObject.list(); } catch (RuntimeException re) { log.error("find by HQL ", re); throw re; } finally{ closeSession(); } } /** * 根据对象名和对象属性查询数据 * @param className * @param propertyName * @param value * @return 实体对象列表 */ @SuppressWarnings("unchecked") public List
findByProperty(String className,String propertyName, Object value) { log.debug("finding "+className+" instance with property: " + propertyName + ", value: " + value); try { String hql = "FROM "+className+" as o WHERE o."+propertyName+" = ?"; Query queryObject = getSession().createQuery(hql); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } finally{ closeSession(); } } /** * 根据HQL查询数据 * @param hql * @return 实体对象列表 */ @SuppressWarnings("rawtypes") public List findByHql(String hql) { log.debug(hql); try { Query queryObject = getSession().createQuery(hql); return queryObject.list(); } catch (RuntimeException re) { log.error("find by HQL ", re); throw re; } finally{ closeSession(); } } /** * 方案一、获取分页对象,实现分页获取数据的功能 * @param hql 查询数据的HQL * @param page 需要显示数据的页码 * @param pageSize 每页数据量 * @return Object[0]当前页的数据列表List ,Object[1]总页数,Object[2]总数量 */ @SuppressWarnings("rawtypes") public Object[] findPageByHql(final String hql, String hqlCount, final int page, final int pageSize) { log.debug(hql); List list = new ArrayList(); //总记录数 Long total = new Long(0); //总页数 Integer totalPage = 0; try { //1、根据hql语句查询指定数据 Query qList = getSession().createQuery(hql); qList.setFirstResult(page * pageSize); qList.setMaxResults(pageSize); list = qList.list(); //2、根据hql语句查询总记录数 List listCount = findByHql(hqlCount); if(listCount!=null && listCount.size()>0){ total = (Long)listCount.get(0); } //3、根据总记录数计算出总页数,ceil进1 totalPage = (int) Math.ceil((double) total.longValue() / pageSize); } catch (Exception e) { e.printStackTrace(); }finally{ closeSession(); } return new Object[] { list, totalPage, total }; } /** * 方案二、通过分页对象,实现分页获取数据的功能 * @param hql 查询数据的HQL * @param page 分页对象 * @return page 分页对象 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public Page findPageByHql(final String hql, String hqlCount, Page page) { log.debug(hql); try { if(page != null){ //1、根据hql语句查询指定数据 Query qList = getSession().createQuery(hql); qList.setFirstResult(page.getStartRow()); qList.setMaxResults(page.getSize()); page.setList(qList.list());//将数据集合保存到page对象 //2、根据hql语句查询总记录数 List listCount = findByHql(hqlCount); if(listCount!=null && listCount.size()>0){ page.setTotalCount(Integer.parseInt(String.valueOf(listCount.get(0))));//将总记录数保存到page对象 } } } catch (Exception e) { e.printStackTrace(); }finally{ closeSession(); } return page; }}

 

------------------------------

public class BaseDaoImpl
{ // 保存当前运行类的参数化类型中的实际的类型 private Class clazz; // 表名 private String tableName; // 构造函数: 1. 获取当前运行类的参数化类型; 2. 获取参数化类型中实际类型的定义(class) public BaseDaoImpl(){ // this 表示当前运行类 (假设是AccountDao或AdminDao) // this.getClass() 当前运行类的字节码(AccountDao.class或AdminDao.class) // this.getClass().getGenericSuperclass(); 当前运行类的父类,即为BaseDaoImpl
// 其实就是“参数化类型”, ParameterizedType Type type = this.getClass().getGenericSuperclass(); // 强制转换为“参数化类型” 【BaseDaoImpl
】 ParameterizedType pt = (ParameterizedType) type; // 获取参数化类型中,实际类型的定义 【new Type[]{Account.class}】 Type types[] = pt.getActualTypeArguments(); // 获取数据的第一个元素:Accout.class clazz = (Class) types[0]; // 表名 (与类名一样,只要获取类名就可以) tableName = clazz.getSimpleName(); }

 

 

转载地址:http://hqlii.baihongyu.com/

你可能感兴趣的文章
postgresql监控工具pgstatspack的安装及使用
查看>>
【JAVA数据结构】双向链表
查看>>
【JAVA数据结构】先进先出队列
查看>>
谈谈加密和混淆吧[转]
查看>>
乘法逆元
查看>>
Objective-C 基础入门(一)
查看>>
Linux系统中的美
查看>>
一些实战项目(linux应用层编程,多线程编程,网络编程)
查看>>
STM32CubeMX 真的不要太好用
查看>>
不要买铝合金机架的无人机,不耐摔,易变形弯曲。
查看>>
ACfly也是基于FreeRTOS的
查看>>
realsense-ros里里程计相关代码
查看>>
似乎写个ROS功能包并不难,你会订阅话题发布话题,加点逻辑处理,就可以写一些基础的ROS功能包了。
查看>>
我觉得在室内弄无人机开发装个防撞机架还是很有必要的,TBUS就做得很好。
查看>>
serial也是见到很多次了,似乎它就是一种串行通信协议
查看>>
TBUS的一些信息
查看>>
专业和业余的区别就在于你在基础在基本功打磨练习花的时间
查看>>
通过mavlink实现自主航线的过程笔记
查看>>
这些网站有一些嵌入式面试题合集
查看>>
我觉得刷题是有必要的,不然小心实际被问的时候懵逼,我觉得你需要刷个50份面试题。跟考研数学疯狂刷卷子一样!
查看>>