微豆之眼

  • 首页
  • GPTs定制
  • 幻兽帕鲁
    • 幻兽帕鲁私服搭建
    • 幻兽帕鲁游戏下载
  • 个人项目
    • 彩云智能助手
    • 开发工具集锦
  • 技术手册
    • PHP 中文手册
    • PHP 函数索引
    • Python 手册
    • JAVA8 手册
    • JAVA11 手册
  • 瑞安学车
  • 关于自己
  1. 首页
  2. Java
  3. 正文

Hibernate DB操作基类

2014年8月24日 2865点热度 1人点赞 0条评论

BaseDAOHibernate.java操作基类如下:

Source code   
public class BaseDAOHibernate extends ExtendedHibernateDaoSupport implements DAO {
    protected final Log log = LogFactory.getLog(getClass());
 
 
    public void saveObject(Object o) {
        getHibernateTemplate().saveOrUpdate(o);
    }
 
 
    public Object getObject(Class clazz, Serializable id) {
        Object o = getHibernateTemplate().get(clazz, id);
 
        if (o == null) {
            throw new ObjectRetrievalFailureException(clazz, id);
        }
 
        return o;
    }
 
 
    public List getObjects(Class clazz) {
        return getHibernateTemplate().loadAll(clazz);
    }
 
 
    public void removeObject(Class clazz, Serializable id) {
        getHibernateTemplate().delete(getObject(clazz, id));
    }
 
    public void removeObject(Object o) {
    	getHibernateTemplate().delete(o);
    }
 
 
    //~ Convenience find methods  ============================================
 
	protected List findByCriteria(final CriteriaBuilder criteriaBuilder) {
    	return findByCriteria(criteriaBuilder, -1, -1).getData();
    }
 
    protected Result findByCriteria(final CriteriaBuilder criteriaBuilder, final int start, final int limit) {
    	return (Result) getReadOnlyHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Criteria criteria = null;
 
				int count = -1;
				if (start != -1 && limit != -1) {
					criteria = criteriaBuilder.buildCountCriteria(session);
					if (criteria != null) {
						count = ((Integer) criteria.list().iterator().next()).intValue();
					}
				}
 
				criteria = criteriaBuilder.buildCriteria(session);
 
				if (start >= 0) {
					criteria.setFirstResult(start);
				}
 
				if (limit >= 0) {
					criteria.setMaxResults(limit + 1);
				}
 
				List data = criteria.list();
 
				Result result = new Result(start, limit);
				result.setTotal(count == -1 ? data.size() : count);
				result.setData(data);
 
				return result;
			}
		});
    }
 
 
    protected List find(String queryString, int limit) {
    	return find(queryString, null, 0, limit).getData();
    }
 
    protected List find(String queryString, Object[] values) {
    	return find(queryString, values, -1, -1).getData();
    }
 
    protected List find(String queryString, Object[] values, Type[] types) {
    	return find(queryString, values, types, -1, -1).getData();
    }
 
    protected Result find(String queryString, Object parameter, int start, int limit) {
    	return find(queryString, new Object[] { parameter }, start, limit);
    }
 
    protected Result find(String queryString, int start, int limit) {
    	return find(queryString, null, start, limit);
    }
 
    protected Result find(String queryString, Object[] values, int start, int limit) {
		return find(queryString, values, null, start, limit);
    }
 
    protected Result find(String queryString, Object[] values, Type[] types, int start, int limit) {
    	return find(null, queryString, values, types, start, limit, true);
    }
 
    protected Result find(String countQueryString, String queryString, Object parameter, int start, int limit) {
    	return find(countQueryString, queryString, new Object[] { parameter }, null, start, limit, true);
    }
 
    protected List findForUpdate(String queryString, Object[] values, Type[] types) {
    	return findForUpdate(null, queryString, values, types, -1, -1).getData();
    }
 
    protected Result findForUpdate(String countQueryString, String queryString, Object[] values, Type[] types, int start, int limit) {
    	return find(countQueryString, queryString, values, types, start, limit, false);
    }
 
    protected Result find(String countQueryString, 
    		String queryString, 
    		Object[] values, Type[] types, 
    		int start, int limit) {
    	return find(countQueryString, queryString, values, types, start, limit, true);
    }
 
    protected Result find(final String countQueryString, 
    						final String queryString, 
    						final Object[] values, final Type[] types, 
    						final int start, final int limit, boolean readOnly) {
 
    	Result result = new Result(start, limit);
 
    	if (countQueryString != null && start != -1 && limit != -1) {
    		result.setTotal(count(countQueryString, values, types));
    	}
 
    	HibernateTemplate ht = readOnly ? getReadOnlyHibernateTemplate() : getHibernateTemplate();
 
    	List data = ht.executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query queryObject = session.createQuery(queryString);
 
				setParameters(queryObject, values, types);
 
				if (start >= 0) {
					queryObject.setFirstResult(start);
				}
 
				if (limit >= 0) {
					queryObject.setMaxResults(limit + 1);
				}
 
				return queryObject.list();
			}
		});
 
		result.setData(data);
 
		if (start == -1 && limit == -1) {
			result.setTotal(data.size());
		}
 
		return result;
    }
 
    protected int count(String queryString) {
    	return count(queryString, null);
    }
 
    protected int count(String queryString, Object[] vlaues) {
    	return count(queryString, vlaues, null);
    }
 
    protected int count(final String queryString, final Object[] values, final Type[] types) {
    	Integer result = (Integer) getReadOnlyHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query queryObject = session.createQuery(queryString);
 
				setParameters(queryObject, values, types);
 
				return queryObject.uniqueResult();
			}
		}
    	);
 
    	return result.intValue();
    }
 
    protected int bulkUpdate(final String queryString, final Object[] values, final Type[] types) throws DataAccessException {
		Integer updateCount = (Integer) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query queryObject = session.createQuery(queryString);
				setParameters(queryObject, values, types);
				return new Integer(queryObject.executeUpdate());
			}
		}, true);
		return updateCount.intValue();
	}
 
    static void setParameters(Query queryObject, Object[] values, Type[] types) {
    	if (values != null) {
			if (types != null) {
				for (int i = 0; i < values.length; i++) {
					queryObject.setParameter(i, values[i], types[i]);
				}
			} else {
				for (int i = 0; i < values.length; i++) {
					queryObject.setParameter(i, values[i]);
				}
			}
		}
    }
 
    protected List findBySQL(final String sql,
    		final String entityAlias, final Class entityClass,
    		final Object[] values, final Type[] types) {
    	return findBySQL(null, sql, entityAlias, entityClass, values, types, -1, -1).getData();
    }
 
    protected Result findBySQL(final String countSql, 
    		final String sql, 
    		final String entityAlias, final Class entityClass,
    		final Object[] values, final Type[] types, 
    		final int start, final int limit) {
    	return findBySQL(countSql, sql, entityAlias, entityClass, values, types, start, limit, true);
    }
 
    protected Result findBySQL(final String countSql, 
    		final String sql, 
    		final String entityAlias, final Class entityClass,
    		final Object[] values, final Type[] types, 
    		final int start, final int limit, boolean readOnly) {
 
    	HibernateTemplate ht = readOnly ? getReadOnlyHibernateTemplate() : getHibernateTemplate();
 
    	Result result = new Result(start, limit);
 
    	if (countSql != null && start != -1 && limit != -1) {
    		Number count = (Number) ht.execute(new HibernateCallback() {
    			public Object doInHibernate(Session session) throws HibernateException, SQLException {
    				return session.createSQLQuery(countSql).setParameters(values, types).uniqueResult();
    			}
			});
    		result.setTotal(count.intValue());
    	}
 
    	List data = ht.executeFind(new HibernateCallback() {
    		public Object doInHibernate(Session session) throws HibernateException {
    			SQLQuery query = session.createSQLQuery(sql);
 
    			query.addEntity(entityAlias, entityClass);
    			query.setParameters(values, types);
 
    			if (start >= 0) {
    				query.setFirstResult(start);
    			}
 
    			if (limit >= 0) {
    				query.setMaxResults(limit + 1);
    			}
 
    			return query.list();
    		}
    	});
 
    	result.setData(data);
 
    	if (start == -1 && limit == -1) {
    		result.setTotal(data.size());
    	}
 
    	return result;
    }
}


ExtendedHibernateDaoSupport.java这个类就是继承HibernateDaoSupport很简单,因为我在项目中可能做了一个读写分离所以我写了一个类,现在这个类如下:

 

Source code   
public class ExtendedHibernateDaoSupport extends HibernateDaoSupport {
 
	private HibernateTemplate readOnlyHibernateTemplate = null;
 
	public void setReadOnlySessionFactory(SessionFactory sessionFactory) {
		this.readOnlyHibernateTemplate = new HibernateTemplate(sessionFactory);
		this.readOnlyHibernateTemplate.setFlushMode(HibernateAccessor.FLUSH_NEVER);
	}
 
	public HibernateTemplate getReadOnlyHibernateTemplate() {
		return (readOnlyHibernateTemplate == null) ? getHibernateTemplate() : readOnlyHibernateTemplate;
	}
}

 

DAO.java接口这个定义就更加简单定义一些DB基本操作,写入对象,更新对象,删除对象这个类如下:

Source code   
public interface DAO {
 
    /**
     * Generic method used to get all objects of a particular type. This
     * is the same as lookup up all rows in a table.
     * @param clazz the type of objects (a.k.a. while table) to get data from
     * @return List of populated objects
     */
    public List getObjects(Class clazz);
 
    /**
     * Generic method to get an object based on class and identifier. An 
     * ObjectRetrievalFailureException Runtime Exception is thrown if 
     * nothing is found.
     * 
     * @param clazz model class to lookup
     * @param id the identifier (primary key) of the class
     * @return a populated object
     * @see org.springframework.orm.ObjectRetrievalFailureException
     */
    public Object getObject(Class clazz, Serializable id);
 
    /**
     * Generic method to save an object - handles both update and insert.
     * @param o the object to save
     */
    public void saveObject(Object o);
 
    /**
     * Generic method to delete an object based on class and id
     * @param clazz model class to lookup
     * @param id the identifier (primary key) of the class
     */
    public void removeObject(Class clazz, Serializable id);
 
    /**
     * Generic method to delete an object
     * @param o the object to be deleted
     */
    public void removeObject(Object o);
}

希望对使用hibernate同学有所帮助。

 

标签: 暂无
最后更新:2023年12月9日

zhangsongfu

这个人很懒,什么都没留下

点赞
下一篇 >

文章评论

您需要 登录 之后才可以评论

zhangsongfu

这个人很懒,什么都没留下

最新 热点 随机
最新 热点 随机
推荐15个免费的AI绘画工具和网站 基于 Postfix、Dovecot 和 Mailman 构建企业邮局系统 FC模拟器网页版_按键说明 特斯拉汽车又再一次涨价 亚马逊鼓励员工辞职搞快递服务 苹果与高通达成和解个人感想
奔驰女车主维权的个人感想 Jetty1.6+Solr4.4+mmseg4j(搜狗分词) Nginx 正向代理配置 淘宝分布式文件存储系统-centos6.5+64位编译和安装 linux的服务器Doc,Pdf,Html,Txt之间文件格式处理 瑞幸咖啡新零售模式有感

COPYRIGHT © 2024 微豆之眼. ALL RIGHTS RESERVED.

浙ICP备18014576号-1

浙公网安备33010602009228号