Hibernate查询,返回new对象(注意这个新定义的类要有构造函数),使用sql带条件分页查询并且把结果显示到一个对象的集里面的解决方案



IIndexDao

package com.ucap.netcheck.dao;

import com.ucap.netcheck.combination.beans.IndexCombinationBean;
import com.ucap.netcheck.common.Page;
import com.ucap.netcheck.common.dao.GenericDao;
import com.ucap.netcheck.entity.Site;

/**  
 * @Title: IIndexDao.java
 * @Package com.ucap.netcheck.index.dao
 * @Description:
 * @author Zuoquan Tu
 * @date 2015-4-6 下午6:35:31
 * @version V1.0  
 */
public interface IIndexDao {
 
 /**
   * queryJoinedActivity(通过这个方法实现获取首页的分页信息)
   *
   * @Title: queryJoinedActivity
   * @Description: 通过这个方法实现获取首页的分页信息
   * @param @param pageNo 要查找的页数
   * @param @param pageRow 每页显示记录数
   * @param @param params 查找条件
   * @param @return 设定文件
   * @return Page<IndexCombinationBean>  返回首页制定页面的结果集的结果集
   * @throws
  */
 public Page<IndexCombinationBean> queryIndexInfoByPage(
   int pageNo,int pageRow, Object... params);
}

IndexDaoImpl

package com.ucap.netcheck.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ucap.netcheck.combination.beans.IndexCombinationBean;
import com.ucap.netcheck.common.Page;
import com.ucap.netcheck.common.dao.BaseDAO;
import com.ucap.netcheck.dao.IIndexDao;
import com.ucap.netcheck.entity.CheckService;
import com.ucap.netcheck.entity.Site;
import com.ucap.netcheck.entity.SiteService;
import com.ucap.netcheck.entity.TaskStatus;
import com.ucap.netcheck.exception.DAOException;

/**  
 * @Title: IndexDaoImpl.java
 * @Package com.ucap.netcheck.index.dao
 * @Description:
 * @author Zuoquan Tu
 * @date 2015-4-6 下午6:37:29
 * @version V1.0  
 */
@Repository
@Transactional
public class IndexDaoImpl extends BaseDAO implements IIndexDao {
 
 /**
  * 通过条件查询分页信息
  * params[0]:表示检查名称
  * params[1]:表示首页网址
  * params[2]:表示网站标识码
  * params[3]:表示当前状态
  * params[4]:表示的是用户id
  */
 @SuppressWarnings("unchecked")
 public Page<IndexCombinationBean> queryIndexInfoByPage(
   int pageNo,int pageRow, Object... params) {
  try {
   //Map<String, Object> map = new HashMap<String, Object>();
   List<Object> lists = new ArrayList<Object>();
   String sql = "SELECT new com.ucap.netcheck.combination.beans.IndexCombinationBean(" +
                  "s.wzmc,s.url,s.siteCode,cs.taskStatus,cs.taskRunNum," +
                  "cs.taskOpenNum,cs.userId) " +
          "FROM " + Site.class.getSimpleName() + " s,"
                  + CheckService.class.getSimpleName() + " cs,"
                  + SiteService.class.getSimpleName() + " ss "  +
          "WHERE ss.siteCode = s.siteCode AND ss.servId = cs.servId ";
   
   //通过网站名称进行查询
   if (StringUtils.isNotBlank((String)params[0])) {
    sql += " AND s.wzmc like ? ";
    lists.add("%" + (String)params[0] + "%");
   }
   if (StringUtils.isNotBlank((String)params[1])) {
    sql += " AND s.url like ? ";
    lists.add("%" + (String)params[1] + "%");
   }
   if (StringUtils.isNotBlank((String)params[2])) {
                sql += " AND s.siteCode like ? ";
                lists.add("%" + (String)params[2] + "%");
   }
   if (null != (TaskStatus)params[3]) {
    //sql += " AND cs.taskStatus like ? ";
    //lists.add("%" + (String)params[3] + "%");
    
    sql += " AND cs.taskStatus =?";
    lists.add((TaskStatus)params[3]);
    
    
   }
   if (null != (Integer)params[4]) {
    sql += " AND cs.userId =? ";
    lists.add((Integer)params[4]);
   }
   
   Page<IndexCombinationBean> pages = this.queryByPage(sql, pageNo, pageRow, lists);
   
   //System.out.println("pages.getRecordList().size() = " + pages.getRecordList().size());
   return pages;
  } catch (Exception ex) {
   throw new DAOException("分页查询所有->ERROR", ex);
  }
 }
}

IndexCombinationBean
package com.ucap.netcheck.combination.beans;

import com.ucap.netcheck.entity.TaskStatus;

/**  
 * @Title: IndexCombinationBean.java
 * @Package com.ucap.netcheck.combination.beans
 * @Description: 对应site表,task表,SiteService,CheckService表中的内容,供首页使用
 * @author Tuzuoquan
 * @date 2015-4-6 下午6:54:50
 * @version V1.0  
 */
public class IndexCombinationBean {
    /**
     * 网站名称
     */
 private String wzmc;
 
 /**
  * 首页地址
  */
 private String url;
 
 /**
  * 网站标识码,对应task表中的uuid
  */
 private String siteCode;
 
 /**
  * 任务状态
  */
 private TaskStatus taskStatus;
 
 /**
  * 任务执行了的次数
  */
 private int taskRunNum;
 
 /**
  * 任务开通总次数
  */
 private int taskOpenNum;
 
 /**
  * 用户id
  */
 private int userId;

public IndexCombinationBean(String wzmc, String url, String siteCode,
   TaskStatus taskStatus, int taskRunNum, int taskOpenNum, int userId) {
  this.wzmc = wzmc;
  this.url = url;
  this.siteCode = siteCode;
  this.taskStatus = taskStatus;
  this.taskRunNum = taskRunNum;
  this.taskOpenNum = taskOpenNum;
  this.userId = userId;
 }

public String getWzmc() {
  return wzmc;
 }

public void setWzmc(String wzmc) {
  this.wzmc = wzmc;
 }

public String getUrl() {
  return url;
 }

public void setUrl(String url) {
  this.url = url;
 }

public String getSiteCode() {
  return siteCode;
 }

public void setSiteCode(String siteCode) {
  this.siteCode = siteCode;
 }

public TaskStatus getTaskStatus() {
  return taskStatus;
 }

public void setTaskStatus(TaskStatus taskStatus) {
  this.taskStatus = taskStatus;
 }

public int getTaskRunNum() {
  return taskRunNum;
 }

public void setTaskRunNum(int taskRunNum) {
  this.taskRunNum = taskRunNum;
 }

public int getTaskOpenNum() {
  return taskOpenNum;
 }

public void setTaskOpenNum(int taskOpenNum) {
  this.taskOpenNum = taskOpenNum;
 }

public int getUserId() {
  return userId;
 }

public void setUserId(int userId) {
  this.userId = userId;
 }
}

=====================================================================

要转换成的对象:

package com.kuman.cartoon.entity.admin;

/**
 * 用于分类导航部分的显示
 * @author toto
 */
public class CategoryNavigationBean {
 
 private Integer id;
 
 /**
  * 内容ID
  */
 private Integer nrid;
 
 /**
  * 封面
  */
 private String cover;
   
    /**
     * 文件路径+文件名称,在附件表中
     */
    private String file_path;
   
    /**
     * 文件名,在附件表中
     */
    private String file_name;
   
    /**
     * 名称(标题)
     */
    private String mc;
   
    /**
     * 作者
     */
    private String zz;
   
    /**
     * 类型
     */
    private String type;
   
    /**
     * 采集日期(时间)
     */
    private String cj_date;
   
    /**
     * 序号
     */
    private int porder;
   
    /**
     * 排行类型
     */
    private int categoryCycle;
   
 public String getCover() {
  return cover;
 }

public void setCover(String cover) {
  this.cover = cover;
 }

public Integer getNrid() {
  return nrid;
 }

public void setNrid(Integer nrid) {
  this.nrid = nrid;
 }

public String getFile_path() {
  return file_path;
 }

public void setFile_path(String file_path) {
  this.file_path = file_path;
 }

public String getFile_name() {
  return file_name;
 }

public void setFile_name(String file_name) {
  this.file_name = file_name;
 }

public String getMc() {
  return mc;
 }

public void setMc(String mc) {
  this.mc = mc;
 }

public String getZz() {
  return zz;
 }

public void setZz(String zz) {
  this.zz = zz;
 }

public String getType() {
  return type;
 }

public void setType(String type) {
  this.type = type;
 }

public String getCj_date() {
  return cj_date;
 }

public void setCj_date(String cj_date) {
  this.cj_date = cj_date;
 }

public int getPorder() {
  return porder;
 }

public void setPorder(int porder) {
  this.porder = porder;
 }

public Integer getId() {
  return id;
 }

public void setId(Integer id) {
  this.id = id;
 }

public int getCategoryCycle() {
  return categoryCycle;
 }

public void setCategoryCycle(int categoryCycle) {
  this.categoryCycle = categoryCycle;
 }
}
分页查询部分的代码:

/**
  * 按照条件查找到分类导航所需的信息
  */
 @Override
 @Transactional(propagation = Propagation.REQUIRED)
 public Page findCategoryNavigation(int page, int rows, String mc,
   Integer type, Integer categoryCycle) {
  try {
   List<Object> params = new ArrayList<Object>();
   String sql = "select t.id,c.nrid,a.file_path || '/' || a.file_name as cover," +
                  "a.file_path,a.file_name,c.mc,c.zz,c.type,c.cj_date,t.porder,t.category_cycle as categoryCycle " +
          "from DM_CATEGORY_NAVIGATION t,DM_CONTENT c,DM_AFFIX a " +
                         "where c.nrid = t.content_id " + 
                         "and a.nrid = c.nrid " + 
                         "and a.nrid = t.content_id " +
                         "and a.file_type = 'HZHB_YLTS' ";
   
   //标题
   if (StringUtils.isNotBlank(mc)) {
    sql += "and c.mc like ? ";
    params.add("%" + mc + "%");
   }
   //类型
   if (null != type) {
    sql += "and c.type = ? ";
    params.add(type);
   }
   //排行类型:1.日,2.周,3.月
   if (null != categoryCycle) {
    sql += "and t.category_cycle = ? ";
    params.add(categoryCycle);
   }
   sql += "order by  t.porder desc";
   
   SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sql);
   for (int i = 0; i < params.size(); i++) {
    query = (SQLQuery) query.setParameter(i, params.get(i));
   }
   query.addScalar("id",StandardBasicTypes.INTEGER)
        .addScalar("nrid", StandardBasicTypes.INTEGER)
        .addScalar("cover",StandardBasicTypes.STRING)
        .addScalar("file_path",StandardBasicTypes.STRING)
        .addScalar("file_name",StandardBasicTypes.STRING)
        .addScalar("mc",StandardBasicTypes.STRING)
        .addScalar("zz", StandardBasicTypes.STRING)
        .addScalar("type", StandardBasicTypes.STRING)
        .addScalar("cj_date",StandardBasicTypes.STRING)
        .addScalar("porder", StandardBasicTypes.INTEGER)
        .addScalar("categoryCycle",StandardBasicTypes.INTEGER)
     .setResultTransformer(Transformers.aliasToBean(CategoryNavigationBean.class));
   
   Page pageInfo = new Page();
   pageInfo.setPageNum(page);
   pageInfo.setNumPerPage(rows);
   
   pageInfo.setAllRows(query.list().size());
   
   query.setFirstResult((page - 1) * rows);
   query.setMaxResults(rows);
   pageInfo.setRecordList(query.list());
   
   int allPages = pageInfo.getAllRows() / pageInfo.getNumPerPage();
   if (pageInfo.getAllRows() % pageInfo.getNumPerPage() == 0) {
    pageInfo.setAllPages(allPages);
   } else {
    //总页数
    pageInfo.setAllPages(allPages + 1);
   }
   return pageInfo;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }



上一篇:【java】spring-data-jpa 集成hibernate实现多条件分页查询


下一篇:C# - DataValid数据验证类