大侠们集成ssh以后,关于dao层的BaseDao都怎么用滴?
是直接使用spring提供的HibernateDaoSupport还是写个子类自己写CRUD?
代码发来看看下
谢谢

解决方案 »

  1.   

     交给spring 处理啊,并有spring注入啊
       找个小的demo来看看吧。
       csdn 有相关资料下的
      

  2.   

    如果你DAO是使用Hibernate的话,一般来说BaseDaoImpl这个类会从HibernateDaoSupport这个类做继承,并且实现BaseDao这个接口,里面写一些通用的方法,具体CRUD还是使用spring对Hibernate的包装类HibernateTemplate来实现
    BaseDao代码
    public interface BaseDao { public PaginatedList getPaginatedList(String queryString, int page,
    int pageSize) throws DataAccessException; public PaginatedList getPaginatedList(String queryString, Object obj,
    int page, int pageSize) throws DataAccessException; public PaginatedList getPaginatedList(String queryString, Object[] obj,
    int page, int pageSize) throws DataAccessException;
    //查询
    public List findObjects(String queryString) throws DataAccessException; public List findAllEntitys(String hql, int startRow, int size)
    throws DataAccessException;
    //增加
    public Serializable saveObject(Object o) throws DataAccessException; public Object loadObject(Class objectClass, Serializable id)
    throws DataAccessException;
    //删除
    public void deleteObject(Class entityClass, Serializable id)
    throws DataAccessException; public void deleteObject(Object entity) throws DataAccessException; public void deleteAllObjects(List entities) throws DataAccessException;
    //修改
    public void updateObject(Object entity) throws DataAccessException; public List filterCollection(Set set, String string)
    throws DataAccessException; public void clearSession() throws DataAccessException; public Session useSession() throws DataAccessException; public void useInitialize(Object object) throws DataAccessException; public List findObjects(String queryString, Object[] objects)
    throws DataAccessException; public void saveOrUpdate(Object o) throws DataAccessException;
    //记录集
    public Integer getRecordCount(String sql) throws DataAccessException; public void updateMonydate(String sql); public boolean validateName(Room room); public List export(String sql);
    }
    BaseDaoImpl代码
    public class BaseDaoImpl extends HibernateDaoSupport implements Dao{
    protected final Log log = LogFactory.getLog(getClass());
    public daoImpl(){

    }
    // 分页方法
    public PaginatedList getPaginatedList(String queryString, int page,
    int pageSize) throws DataAccessException {
    return getPaginatedList(queryString, null, page, pageSize);
    }
    public PaginatedList getPaginatedList(String queryString, Object obj,
    int page, int pageSize) throws DataAccessException {
    Object[] object = obj == null ? null : new Object[] { obj };
    return getPaginatedList(queryString, object, page, pageSize);
    } public PaginatedList getPaginatedList(String queryString, Object[] obj,
    int page, int pageSize) throws DataAccessException {
    Session session = null;
    String countHql = null;
    List rsList = null;
    int size = 0;
    int pages = 0;
    PropertiesReader reader = PropertiesReader
    .getIntance("/conf.properties");
    if (pageSize == 0) {
    //每页显示多少条记录pagesize
    pageSize = reader.getInt(Constants.PAGE_SIZE).intValue();
    }
    if (page < 1) {
    page = 1;//page 当前页
    }
    countHql = this.getQuery(queryString);
    Iterator it = (obj != null) ? getHibernateTemplate().iterate(countHql,
    obj) : getHibernateTemplate().iterate(countHql);
    if (it.hasNext())
    size = Integer.parseInt(it.next().toString());
    //size一共多少条记录
    pages = StringUtils.getPages(size, pageSize);//一共可分多少页
    try {
    session = super.getSession();
    Query query = session.createQuery(queryString);
    if (obj != null) {
    for (int i = 0; i < obj.length; i++) {
    query.setParameter(i, obj[i]);
    }
    }
    //Query query=session.createSQLQuery(queryString);
    query.setFirstResult((page - 1) * pageSize);
    query.setMaxResults(pageSize);
    rsList = query.list();//反回的记录结果集

    } catch (Exception e) {
    log.trace(e);
    }
    PaginatedList pList = new PaginatedList();
    pList.addAll((rsList == null) ? new ArrayList() : rsList);
    pList.setCurrentPage(page);//设置当前页
    pList.setPages(pages);//一共多少页
    pList.setTotleCount(size);//一共多少条记录
    pList.setPageSize(pageSize);//每面显示多少条记录
    int index = ((page - 1) * pageSize) + 1;//设置下一页的开始
    pList.setNextIndex(index);
    return pList; } // 由一条hql语句得到查询总记录条数hql语句
    private String getQuery(String queryStr) {
    String sql = "";
    if (queryStr != null && queryStr.trim().length() != 0) {
    if (queryStr.indexOf("SELECT") == -1
    && queryStr.indexOf("select") == -1) {
    sql = "Select Count(*)  " + queryStr;
    } else {
    sql = "Select Count(*)  From (" + queryStr + ")";
    }
    // int index = 0;
    // if (sql.indexOf("ORDER") != -1) {
    // index = sql.indexOf("ORDER");
    // }
    // if (sql.indexOf("order") != -1) {
    // index = sql.indexOf("order");
    // }
    // if (index != 0) {
    // sql = sql.substring(0, index);
    // }
    }
    return sql;
    } // 查询记录总数
    public Integer getRecordCount(String queryString)
    throws DataAccessException {
    String countHql = null;
    int size = 0;
    countHql = this.getQuery(queryString);
    Iterator it = getHibernateTemplate().iterate(countHql);
    if (it.hasNext())
    size = Integer.parseInt(it.next().toString());
    return size;
    } // 根据hql语句查询所有实体� public List findObjects(String queryString) throws DataAccessException {
    return super.getHibernateTemplate().find(queryString);


    } // ecside翻页标签使用的方法� public List findAllEntitys(String hql, int startRow, int size) {
    return this.getSession().createQuery(hql).setFirstResult(startRow)
    .setMaxResults(size).list();
    } // 使用带命名的参数的hql语句检索数据� public List findObjects(String queryString, Object[] objects)
    throws DataAccessException {
    return super.getHibernateTemplate().find(queryString, objects);
    } // 保存对象
    public Serializable saveObject(Object o) throws DataAccessException {
    Serializable index = (Serializable) super.getHibernateTemplate()
    .save(o);
    //getHibernateTemplate().save(o);
    return index;
    } // 删除对象
    public void deleteObject(Class entityClass, Serializable id)
    throws DataAccessException {
    Object object=this.loadObject(entityClass, id);
    if(object!=null){
    this.getHibernateTemplate().delete(object);
    }
    } public void deleteObject(Object entity) throws DataAccessException {
    super.getHibernateTemplate().delete(entity); } // 批量删除
    public void deleteAllObjects(List entities) throws DataAccessException {
    super.getHibernateTemplate().deleteAll(entities);
    } // 更新对象
    public void updateObject(Object entity) throws DataAccessException {
    super.getHibernateTemplate().update(entity);
    } // 加载一个对象� public Object loadObject(Class objectClass, Serializable id) {
    try {
    Object obj = super.getHibernateTemplate().get(objectClass, id);
    return obj;
    } catch (DataAccessException e) {
    return null;
    }
    } // 过滤集合
    public List filterCollection(Set set, String string)
    throws DataAccessException {
    return super.getSession().createFilter(set, string).list();
    } // 清空session
    public void clearSession() throws DataAccessException {
    this.getSession().clear();
    } // 获取session
    public Session useSession() throws DataAccessException {
    return this.getSession();
    } // 强制加载关联的对象(有延迟加载的时候用)� public void useInitialize(Object object) throws DataAccessException {
    this.getHibernateTemplate().initialize(object);
    } // 保存更新对象
    public void saveOrUpdate(Object o) throws DataAccessException {
    this.getSession().saveOrUpdate(o);
    }
    public void updateMonydate(String sql) {
    SessionFactory session= this.getHibernateTemplate().getSessionFactory();
    Session ses=session.openSession();
    Query query=ses.createSQLQuery(sql);
    //query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);这样可以设置返回的值为list<Map>
    query.executeUpdate();
    ses.close();
    session.close();


    }

    }
      

  3.   

    package com.yeezoo.tour.common.dao;import java.io.Serializable;
    import java.util.List;import org.hibernate.Query;
    import org.hibernate.SQLQuery;
    import org.hibernate.Session;
    import org.hibernate.criterion.Order;
    import org.springframework.orm.hibernate3.HibernateCallback;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import com.yeezoo.tour.common.util.ConverType;/**
     * 
     * 数据管理类
     * @author goxohu
     * 
     */
    public class DataBaseDao extends HibernateDaoSupport implements DataBaseDaoInterface{ /**
     * 保存数据
     * @param obj
     */
    public void save(Object obj) {
    try {
    this.getHibernateTemplate().save(obj);
    } catch (RuntimeException re) {
    throw re;
    }
    }

    /**
     * 修改某个对象中的数据
     * @param obj
     */
    public void saveOrUpdate(Object obj) {
    try {
    this.getHibernateTemplate().saveOrUpdate(obj);
    }catch (RuntimeException re) {
    throw re;
    }
    }

    /**
     * 保存数据
     * @param obj
     */
    public void saveOrUpdateAll(List list) {
    try {
    getHibernateTemplate().saveOrUpdateAll(list);
    } catch (RuntimeException re) {
    throw re;
    }
    } /**
     * 删除某个对象的数据
     * @param cla
     * @param idValue
     */
    public void delete(Class cla, Serializable idValue) {
    try {
    this.delete(this.getHibernateTemplate().get(cla, idValue));
    } catch (RuntimeException re) {
    throw re;
    }
    } /**
     * 删除某个对象的数据
     * @param obj
     */
    public void delete(Object obj) {
    try {
    this.getHibernateTemplate().delete(obj);
    } catch (RuntimeException re) {
    throw re;
    }
    }

    /**
     * 删除一批对象的数据
     * @param obj
     */
    public void deleteAll(List list){
    try {
       this.getHibernateTemplate().deleteAll(list);
    } catch (RuntimeException re) {
    throw re;
    }
    }

    /**
     * 根据对象名和ID值获取当前对象
     * @param cla
     * @param idValue
     * @return
     */
    public <U extends Object>U findById(Class<U> cla, Serializable idValue) {
    try {

    Object obj = this.getHibernateTemplate().get(cla,idValue);
    return (obj != null) ? (U)obj : null;
    } catch (RuntimeException re) {
    throw re;
    }
    }

    /**
     * 等于
     * @param ClassName
     * @param names
     * @param vals
     * @return
     */
    public List findByNamedParam(String className,String[] names,Object[] vals){
    String hql = "form "+className+ " m where 1=1 ";
    //this.getHibernateTemplate().findByNamedParam(queryString, paramNames, values);
    return null;
    } /**
     * 根据HQL查询返回List
     * @param hql
     * @return
     */
    public List findByHql(String hql) {
    try {
    return this.getHibernateTemplate().find(hql);
    } catch (RuntimeException re) {
    throw re;

    } /**
     * 根据SQL查询返回List,list中的元素为Object[]
     * @param sql
     * @return
     * @throws Exception
     */
    public List findBySql(final String sql) throws Exception {
    try{
    return (List)this.getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(Session session){
    SQLQuery q = session.createSQLQuery(sql);
    List list = q.list();
    return q.list();
    }
    });
    }catch (RuntimeException re) {
    throw re;
    }
    }

    /**
     * 根据SQL查询返回List,list中的元素为指定对象
     * @param sql
     * @param tab 
     * @param cla
     * @return
     * @throws Exception
     */
    public List findBySql(final String sql,final String tab,final Class cla) throws Exception {
    try{
    return (List)this.getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(Session session){
    SQLQuery q = session.createSQLQuery(sql);
    q.addEntity(tab, cla);
    return q.list();
    }
    });
    }catch (RuntimeException re) {
    throw re;
    }
    } /**
     * 查询所有数据
     * @param cla
     * @return
     */
    public List findAll(final Class cla) {
    try {
    return (List)this.getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(Session session){
    List list = session.createCriteria(cla).list();
    return list;
    }
    });
    }catch (RuntimeException re) {
    throw re;


    }

    public List findAll(final Class cla , final String orderColName, final String orderType) {
    try {
    return (List)this.getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(Session session){

    return (orderType.equals("desc")) 
       ? session.createCriteria(cla).addOrder(Order.desc(orderColName)).list() 
       : session.createCriteria(cla).addOrder(Order.asc(orderColName)).list();
    }
    });
    }catch (RuntimeException re) {
    throw re;


    }

    /**
     * 查询所有数据
     * @param cla
     * @param orderStr 排序字段
     * @return
     */
    public List findAll(final Class cla,final String orderStr){
    try {
    return (List)this.getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(Session session){

    return session.createCriteria(cla).addOrder(Order.asc(orderStr)).list();
    }
    });
    } catch (RuntimeException re) {
    throw re;


    }

    /**
     * 多参与查询
     * @param hql
     * @param str
     * @param obj
     * @return
     */
    public List findByNamedParamHql(final String hql,final String[] str,final Object[] obj){
    try {
    return (List)this.getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(Session session){
    Query query = session.createQuery(hql);
    if(str!=null && str.length>0){
    for (int i = 0; i < str.length; i++) {
    query.setParameter(str[i], obj[i]);
    }
    }
    return query.list();
    }
    });
    } catch (RuntimeException re) {
    throw re;

    }

    /**
     * 调用存程过程
     * @param cla
     * @param str
     * @return
     */
    public List findBySqlAndEntity(final Class[] cla,final String str){
    try {
    return (List)this.getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(Session session){
    SQLQuery sq=session.createSQLQuery(str);
    if(cla!=null && cla.length>0){
    for (int i = 0; i < cla.length; i++) {
    sq.addEntity("a"+(i+1),cla[i]);
    }
    }
    return sq.list();
    }
    });
    } catch (RuntimeException re) {
    throw re;
    }
    }

        /**
         * 
         * @param proName
         * @param inList
         * @param outSize
         * @return
         */
    public List execProc(final String proName, final List inList, final int outSize){
    try{
    return (List)this.getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(Session session){
    String param = "";
    for (int i=1; i<=inList.size() + outSize; i++){
    if("".equals(param)){
    param = "?";
    } else {
    param += ", ?";
    }
    }
    SQLQuery query = session.createSQLQuery("{CALL dbo." + proName + "(" + param + ")}");
            for (int i=1; i<=inList.size(); i++){
             query.setString(i, ConverType.conver(inList.get(i-1)));
            }

    query.setString(1, "admin");
    List list =query.list();
    return list;
    }
    });
    } catch (RuntimeException re) {
    throw re;
    }
    } public List findByHqlMaxResult(final String hql, final int fromIndex, final int toIndex) {
    try{
    return (List)this.getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(Session session){
    Query q = session.createQuery(hql);
    q.setFirstResult(fromIndex);
    q.setMaxResults(toIndex);
    return q.list();
    }
    });
    }catch (RuntimeException re) {
    throw re;
    }
    }

    public Integer updateHql(final String hql) {
    try{
    return (Integer)this.getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(Session session){
    Query q = session.createQuery(hql);
    return q.executeUpdate();
    }
    });
    }catch (RuntimeException re) {
    throw re;
    }
    }

    public List findBySql(final String sql,final String[] colName,final Object[] colVal)  {
    try{
    return (List)this.getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(Session session){
    SQLQuery q = session.createSQLQuery(sql);
    if(colName != null && colName.length > 0){
    for (int i = 0; i < colName.length; i++) {
    q.setParameter(colName[i], colVal[i]);
    }

    List list = q.list();
    return q.list();
    }
    });
    }catch (RuntimeException re) {
    throw re;
    }
    }


    }