开发者社区> 问答> 正文

ssh 框架 BaseDao怎么写怎么封装?:报错

@卡通嘟嘟 你好,想跟你请教个问题: hibernate Basedao  我不懂可以请教下吗.

展开
收起
kun坤 2020-06-09 11:45:19 541 0
1 条回答
写回答
取消 提交回答
  • 如果需求变化不大!mybatis也是个不错的选择######既然是SSH,那么就交给Spring来管理你的hibernate的sessionFactory, 然后通过sessionFactory来进行相应的数据操作。 Spring和Hibernate的集成,google下,应该有很多标准的配置。######可以看下springside里面的dao,封装的不错######我用ssh做一个增删改查的小案例,用的很模糊,各位朋友可否指导一下呢,小弟谢过了.######

    /** 写一段给你,希望对你有帮助 * / import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.; import org.hibernate.; import org.hibernate.type.Type; import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

    public class BaseHibernateDao extends HibernateDaoSupport {

    public BaseHibernateDao()
    {
    }
    
    public void delete(Object entity)
    {
    	getHibernateTemplate().delete(entity);
    }
    
    public void delete(Serializable id, Class clazz)
    {
    	delete(getEntity(id, clazz));
    }
    
    public void deleteAll(Collection c)
    {
    	for (Iterator iter = c.iterator(); iter.hasNext(); delete(iter.next()));
    }
    
    public void evict(Object entity)
    {
    	getHibernateTemplate().evict(entity);
    }
    
    public void executeSql(String sql)
    {
    	Connection con;
    	Session session = getSession();
    	con = session.connection();
    	PreparedStatement pst = null;
    	try {
    		pst = con.prepareStatement(sql);
    		pst.execute();
    		pst.close();
    	} catch (Exception e) {
    		throw new BusinessException("执行SQL语句时出错!", e);
    	} finally {
    		if (pst != null)
    			try {
    				pst.close();
    			} catch (SQLException e) {
    				throw new BusinessException("执行SQL语句时出错!", e);
    			}
    	}
    }
    
    public void flush()
    {
    	getHibernateTemplate().flush();
    }
    
    private Query genQuery(String hql, Object conditionValues[])
    {
    	Query query = genQuery(hql);
    	setQueryConditionValue(hql, conditionValues, query);
    	return query;
    }
    
    private Query genQuery(String hql)
    {
    	return getSession().createQuery(hql);
    }
    
    public List getEntities(String hql, Object conditionValues[])
    {
    	Query query = genQuery(hql, conditionValues);
    	return query.list();
    }
    
    public List getEntities(String hql)
    {
    	Query query = genQuery(hql);
    	return query.list();
    }
    
    public List getEntities(String hql, Object conditionNames[], Object conditionValues[])
    {
    	Query query = getQuery(hql, conditionNames, conditionValues);
    	return query.list();
    }
    
    public Query getQuery(String hql, Object conditionNames[], Object conditionValues[])
    {
    	if (conditionNames.length != conditionValues.length)
    		throw new BusinessException("参数和值的数组长度不匹配,长度必需相等!");
    	getHibernateTemplate().setCacheQueries(true);
    	Query query = getSession().createQuery(hql);
    	if (conditionValues != null)
    	{
    		for (int i = 0; i < conditionValues.length; i++)
    		{
    			Object param = conditionValues[i];
    			if (param == null)
    				throw new BusinessException((new StringBuilder("执行HQL为:")).append(hql).append(" 查询的时候验证参数出错,第 ").append(i + 1).append(" 个参数值为null!").toString());
    			if (param instanceof Object[])
    				query.setParameterList((String)conditionNames[i], (Object[])param);
    			else
    			if (param instanceof Collection)
    				query.setParameterList((String)conditionNames[i], (Collection)param);
    			else
    				query.setParameter((String)conditionNames[i], param);
    		}
    
    	}
    	return query;
    }
    
    public List getEntitiesByNativeSql(String nativeSql, String kids[], Class clazzs[], Object conditionValues[])
    {
    	SQLQuery query = getSession().createSQLQuery(nativeSql);
    	if (kids.length != clazzs.length)
    		throw new BusinessException("参数和值的数组长度不匹配,长度必需相等!");
    	if (clazzs != null)
    	{
    		for (int i = 0; i < clazzs.length; i++)
    			query.addEntity(kids[i], clazzs[i]);
    
    	}
    	if (conditionValues != null)
    	{
    		for (int i = 0; i < conditionValues.length; i++)
    		{
    			Object param = conditionValues[i];
    			if (param == null)
    				throw new BusinessException((new StringBuilder("执行原生SQL为:")).append(nativeSql).append(" 验证参数时出错,第 ").append(i + 1).append(" 个参数值为null!").toString());
    			if (param instanceof Object[])
    				throw new BusinessException((new StringBuilder("执行原生SQL为:")).append(nativeSql).append(" 验证参数时出错,第 ").append(i + 1).append(" 个参数值为数组!").toString());
    			if (param instanceof Collection)
    				throw new BusinessException((new StringBuilder("执行原生SQL为:")).append(nativeSql).append(" 验证参数时出错,第 ").append(i + 1).append(" 个参数值为列表!").toString());
    			query.setParameter(i, param);
    		}
    
    	}
    	return query.list();
    }
    
    public List getEntitiesByNativeSql(String nativeSql, String kids[], Class clazzs[], Object conditionValues[], String scalars[], Type types[])
    {
    	SQLQuery query = getSession().createSQLQuery(nativeSql);
    	if (clazzs != null)
    	{
    		for (int i = 0; i < clazzs.length; i++)
    			query.addEntity(kids[i], clazzs[i]);
    
    	}
    	return null;
    }
    
    public List getEntitiesByNativeSql(String nativeSql, String kids[], Class clazzs[])
    {
    	SQLQuery query = getSession().createSQLQuery(nativeSql);
    	if (clazzs != null)
    	{
    		for (int i = 0; i < clazzs.length; i++)
    			query.addEntity(kids[i], clazzs[i]);
    
    	}
    	return query.list();
    }
    
    public List getEntitiesByNativeSql(String nativeSql, String kids[], Class clazzs[], String as[], Type atype[])
    {
    	return null;
    }
    
    public Object getEntity(Serializable id, Class clazz)
    {
    	Object entity = getHibernateTemplate().get(clazz, id);
    	return entity != null ? entity : BeanUtil.newInstance(clazz);
    }
    
    public Object insert(Object entity)
    {
    	getHibernateTemplate().save(entity);
    	return entity;
    }
    
    public Object loadEntity(Serializable id, Class clazz)
    {
    	Object entity = getHibernateTemplate().load(clazz, id);
    	return entity != null ? entity : BeanUtil.newInstance(clazz);
    }
    
    public Object save(Object entity)
    {
    	if (LogUtil.getIdentify(entity) == null)
    		getHibernateTemplate().save(entity);
    	else
    		getHibernateTemplate().saveOrUpdate(entity);
    	return entity;
    }
    
    private void setQueryConditionValue(String hql, Object conditionValues[], Query query)
    {
    	if (conditionValues != null)
    	{
    		for (int i = 0; i < conditionValues.length; i++)
    		{
    			Object param = conditionValues[i];
    			if (param == null)
    				throw new BusinessException((new StringBuilder("执行HQL为:")).append(hql).append(" 验证参数时出错,第 ").append(i + 1).append(" 个参数值为null!").toString());
    			if (param instanceof Object[])
    				throw new BusinessException((new StringBuilder("执行HQL为:")).append(hql).append(" 验证参数时出错,第 ").append(i + 1).append(" 个参数值为数组!").toString());
    			if (param instanceof Collection)
    				throw new BusinessException((new StringBuilder("执行HQL为:")).append(hql).append(" 验证参数时出错,第 ").append(i + 1).append(" 个参数值为列表!").toString());
    			query.setParameter(i, param);
    		}
    
    	}
    }
    
    public Object uniqueResult(String hql, Object conditionValues[])
    {
    	Query query = genQuery(hql, conditionValues);
    	return query.uniqueResult();
    }
    
    public Object update(Object entity)
    {
    	getHibernateTemplate().update(entity);
    	return entity;
    }
    
    public void updateOrDelete(String hql)
    {
    	Session session = getSession();
    	Query query = session.createQuery(hql);
    	query.executeUpdate();
    	session.flush();
    	session.clear();
    }
    
    public void updateOrDelete(String hql, Object conditionValues[])
    {
    	Session session = getSession();
    	Query query = session.createQuery(hql);
    	setQueryConditionValue(hql, conditionValues, query);
    	query.executeUpdate();
    	session.flush();
    	session.clear();
    }
    
    public void updateOrDetete(String hql, Map map)
    {
    	Query query = getQuery(hql, map.keySet().toArray(), map.values().toArray());
    	query.executeUpdate();
    	getSession().flush();
    	getSession().clear();
    }
    
    public List getAllEntitys(Class clazz, String sort[])
    {
    	StringBuffer hql = new StringBuffer("select o from ");
    	hql.append(clazz.getName()).append(" o ");
    	String as[];
    	int j = (as = sort).length;
    	for (int i = 0; i < j; i++)
    	{
    		String sor = as[i];
    		if (sor != null && !"".equals(sor))
    			hql.append(" order by ").append(sor);
    	}
    
    	return getEntities(hql.toString());
    }
    
    public PageInfo getEntities_Page(String hql, Object conditionNames[], Object conditionValues[], PageInfo page)
    {
    	Long totalCount = getTotalCount(hql, conditionNames, conditionValues);
    	Long totalPages = new Long((new Double(Math.ceil(totalCount.longValue() / page.getPageSize().longValue()))).intValue());
    	totalPages = Long.valueOf(totalCount.longValue() % page.getPageSize().longValue() != 0L ? totalPages.longValue() + (new Long(1L)).longValue() : totalPages.longValue());
    	PageInfo pageInfo = new PageInfo();
    	pageInfo.setPageSize(page.getPageSize());
    	pageInfo.setPage(page.getPage());
    	pageInfo.setTotalSize(totalCount);
    	pageInfo.setPageCount(totalPages);
    	Query query = getQuery(hql, conditionNames, conditionValues);
    	query.setFirstResult((page.getPage().intValue() - 1) * page.getPageSize().intValue());
    	query.setMaxResults(page.getPageSize().intValue());
    	List list = query.list();
    	pageInfo.setData(list);
    	return pageInfo;
    }
    
    private Long getTotalCount(String hql, Object conditionNames[], Object conditionValues[])
    {
    	Long totalCount = new Long(0L);
    	String lowerhql = hql.toLowerCase();
    	String totalHql = new String("");
    	int fIndex = lowerhql.indexOf(" from ");
    	if (fIndex < 0)
    		fIndex = 0;
    	else
    		fIndex++;
    	int orderLastIndex = lowerhql.lastIndexOf(" order by ");
    	if (orderLastIndex > 0)
    		totalHql = (new StringBuilder("select count(*) ")).append(hql.substring(fIndex, orderLastIndex)).append(" ").toString();
    	else
    		totalHql = (new StringBuilder("select count(*) ")).append(hql.substring(fIndex)).append(" ").toString();
    	List list = getEntities(totalHql, conditionNames, conditionValues);
    	Number num = (Number)list.get(0);
    	totalCount = new Long(num.longValue());
    	return totalCount;
    }
    
    protected User getOper()
    {
    	User oper = (User)SingleThreadImpl.getInstance().get("user_context");
    	return oper;
    }
    

    }

    ######O(∩_∩)O谢谢,非常有用.######批量删除建议修改下,效率太慢.

    2020-06-09 11:45:32
    赞同 展开评论 打赏
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多