Hibernate 使用原生SQL和实体之间的关联

有时候需要在几个表之间进行处理的时候,HIbernate就显得比较捉急,使用原生的SQL更加的好看。将查询的结果和实体关联起来,这种处理的方式也是比较不错的

  1. 查询返回的原生的实体对象
package com.hikvision.cms.modules.dataquery.domain;

import java.io.Serializable;
import java.sql.Timestamp;
/**
 * 查询返回的数据库信息
 * @author wangji
 * @date  2016年6月15日-下午4:35:33
 */
public class TrafficFlowInfo implements Serializable {
    /**
     * @date  2016年6月16日-下午2:54:35
     * @author wangji
     */
    private static final long serialVersionUID = -1082884741253824895L;
    private String carNo;//车牌号码
    private Integer gateNo;//出入口
    private Integer passCount;//过车次数
    private String  gateName;//出入口名称
    private Integer orderNumber;//编号
    public Integer getOrderNumber() {
        return orderNumber;
    }
    public void setOrderNumber(Integer orderNumber) { 
        this.orderNumber = orderNumber;
    }
    public String getGateName() {
        return gateName;
    }
    public void setGateName(String gateName) {
        this.gateName = gateName;
    }

    public String getCarNo() {
        return carNo;
    }
    public void setCarNo(String carNo) {
        this.carNo = carNo;
    }
    public Integer getGateNo() {
        return gateNo;
    }
    public void setGateNo(Integer gateNo) {
        this.gateNo = gateNo;
    }
    public Integer getPassCount() {
        return passCount;
    }
    public void setPassCount(Integer passCount) {
        this.passCount = passCount;
    }

}
  1. DAO层的操作,让他和实体之间关联起来,这个实体不是原生的数据库中的表对象。而是经过几个表操作查询的结果
package com.hikvision.cms.modules.dataquery.dao.impl;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.hikvision.cms.modules.dataquery.domain.TrafficFlowInfo;
import com.hikvision.cms.scaffolding.dao.HibernateEntityDao;

@Repository
public class TrafficFlowInfoDaoImpl extends HibernateEntityDao<TrafficFlowInfo>{

    @SuppressWarnings("unchecked")
    public List<TrafficFlowInfo> sqlQuery(String hql) {
        return getSession()
                .createSQLQuery(hql)
                .addScalar("carNo", Hibernate.STRING) 
                .addScalar("gateNo", Hibernate.INTEGER)
                .addScalar("passCount", Hibernate.INTEGER)
                .setResultTransformer(
                        Transformers.aliasToBean(TrafficFlowInfo.class)).list();
    }
    /**
     * 查询总记录数
     * 
     * @param hql
     * @return List<?>
     */
    public List<?> sqlQueryCount(String hql) {
        return getSession().createSQLQuery(hql).list();
    }

}
  1. ServiceImpl层进行的操作,反射导出Excel
package com.hikvision.cms.modules.dataquery.service.impl;

import java.util.List;

import javax.annotation.Resource;

import jxl.format.Alignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import com.hikvision.cms.modules.dataquery.dao.impl.TrafficFlowInfoDaoImpl;
import com.hikvision.cms.modules.dataquery.domain.TrafficFlowInfo;
import com.hikvision.cms.modules.dataquery.dto.TrafficFlowInfoSearchDto;
import com.hikvision.cms.modules.log.domain.OperationLog;
import com.hikvision.cms.modules.parkingterminio.domain.GateInfo;
import com.hikvision.cms.modules.parkingterminio.service.GateInfoService;
import com.hikvision.cms.scaffolding.dao.support.PageBean;

@Service
public class TrafficFlowServiceImpl {

    @Resource
    private TrafficFlowInfoDaoImpl trafficFlowDao;
    @Resource
    private GateInfoService gateInfoService;
    public GateInfoService getGateInfoService() {
        return gateInfoService;
    }
    public void setGateInfoService(GateInfoService gateInfoService) {
        this.gateInfoService = gateInfoService;
    }
    public TrafficFlowInfoDaoImpl getTrafficFlowDao() {
        return trafficFlowDao;
    }
    public void setTrafficFlowDao(TrafficFlowInfoDaoImpl trafficFlowDao) {
        this.trafficFlowDao = trafficFlowDao;
    }
    public PageBean findPageBean(TrafficFlowInfoSearchDto condiction,Integer pageSize,Integer currentPage,Integer orderType){
        if(orderType == null){
            orderType = -1;
        }

        int allRow = getAllRow(condiction);
        // 当前页开始记录
        int offset = PageBean.countOffset(pageSize, currentPage, allRow);
       // 分页
        String limit = " LIMIT " + pageSize + " OFFSET " + offset;

        String hqlList = finAllTrafficFlowInfoHql(condiction, orderType);

        hqlList += limit;

        List<TrafficFlowInfo> list =trafficFlowDao.sqlQuery(hqlList);
        if(CollectionUtils.isNotEmpty(list)){
            int orderNumber=0;
            for(TrafficFlowInfo Item : list){
                orderNumber++;
                GateInfo gateInfo = gateInfoService.fetchGateById(Item.getGateNo());
                if(gateInfo != null){
                    Item.setGateName(gateInfo.getGateName());//出入口的名称
                }else{
                    Item.setGateName("");
                }
                Item.setOrderNumber(orderNumber);//编号
            }
             return new PageBean(allRow, currentPage, pageSize, list, 0); 
        }
        return new PageBean();  
    }
    private String finAllTrafficFlowInfoHql(TrafficFlowInfoSearchDto dto,Integer orderType){
        // hps_passvehicleinfo.plate_info,hps_passvehicleinfo.gate_id ,count(hps_passvehicleinfo.gate_id) as passCount
        String hql="select "
                +" hps_passvehicleinfo.plate_info as carNo,"
                + " hps_passvehicleinfo.gate_id as gateNo,"
                +" count(hps_passvehicleinfo.gate_id) as passCount"
                +" from hps_passvehicleinfo";
        boolean flag =false;
        if(dto.getParkingId() !=  null && dto.getParkingId()  != -1){//parkId
            flag =true;
            hql+=" where hps_passvehicleinfo.parking_id='"+dto.getParkingId()+"'";
        }
        if(dto.getCarType() != null && dto.getCarType() != -1){//parkType
            if(flag == true){
                hql+=" and hps_passvehicleinfo.vehicle_type='"+dto.getCarType()+"'";
            }else{
                hql+=" where hps_passvehicleinfo.vehicle_type='"+dto.getCarType()+"'";
                flag =true;
            }

        } 
        if(dto.getGateId() !=null  && dto.getGateId() !=-1){
            if(flag == true){
                hql+=" "+"and hps_passvehicleinfo.gate_id = '"+dto.getGateId()+"' ";
            }else{
                hql +=" "+"where hps_passvehicleinfo.gate_id = '"+dto.getGateId()+"' ";
                flag =true;
            }
        }
        if(dto.getBeginTime() !=null && dto.getEndTime() !=null){//passType
            if(flag == true){
                hql+=" and hps_passvehicleinfo.pass_time BETWEEN '"+dto.getBeginTime()+"'"
                        +" and '"+dto.getEndTime()+"'";
            }else{
                hql+=" where hps_passvehicleinfo.pass_time BETWEEN '"+dto.getBeginTime()+"'"
                        +" and '"+dto.getEndTime()+"'";
                flag =true;
            }
        }
        if(dto.getCarNo() != null){
            if(flag ==true){
                hql+=" and hps_passvehicleinfo.plate_info LIKE '%"+dto.getCarNo().toString()+"%'";
            }else{
                hql+=" where hps_passvehicleinfo.plate_info  LIKE '%"+dto.getCarNo().toString()+"%'";
                flag =true;
            }
        }
        hql+=" GROUP by "
             +" hps_passvehicleinfo.plate_info,hps_passvehicleinfo.gate_id";
        switch (orderType) {
            case -1:
                hql+=" order by hps_passvehicleinfo.plate_info "; 
                break;
            case 0:
                hql+=" order by hps_passvehicleinfo.gate_id desc";
                break;
            case 1:
                hql+=" order by passCount desc";
                break;
            default:
                hql+=" order by hps_passvehicleinfo.plate_info ";
                break;
        }
        return hql;             
    }

    private int getAllRow(TrafficFlowInfoSearchDto dto){
        String hql=" select"
                +"  hps_passvehicleinfo.plate_info as carNo,"
                + " hps_passvehicleinfo.gate_id as gateNo,"
                +" count(hps_passvehicleinfo.gate_id) as passCount"
                +" from hps_passvehicleinfo";
        boolean flag =false;
        if(dto.getParkingId() !=  null && dto.getParkingId()  != -1){//parkId
            flag =true;
            hql+=" where hps_passvehicleinfo.parking_id='"+dto.getParkingId()+"'";
        }
        if(dto.getCarType() != null && dto.getCarType() != -1){//parkType
            if(flag == true){
                hql+=" and hps_passvehicleinfo.vehicle_type='"+dto.getCarType()+"'";
            }else{
                hql+=" where hps_passvehicleinfo.vehicle_type='"+dto.getCarType()+"'";
                flag =true;
            }

        }
        if(dto.getBeginTime() !=null && dto.getEndTime() !=null){//passType
            if(flag == true){
                hql+=" and hps_passvehicleinfo.pass_time BETWEEN '"+dto.getBeginTime()+"'"
                        +" and '"+dto.getEndTime()+"'";
            }else{
                hql+=" where hps_passvehicleinfo.pass_time BETWEEN '"+dto.getBeginTime()+"'"
                        +" and '"+dto.getEndTime()+"'";
                flag =true;
            }
        }
        if(dto.getCarNo() != null){
            if(flag ==true){
                hql+=" and hps_passvehicleinfo.plate_info LIKE '%"+dto.getCarNo().toString()+"%'";
                flag =true;
            }else{
                hql+=" where hps_passvehicleinfo.plate_info  LIKE '%"+dto.getCarNo().toString()+"%'";
            }
        }
        if(dto.getGateId() !=null  && dto.getGateId() !=-1){
            if(flag == true){
                hql+=" "+"and hps_passvehicleinfo.gate_id = '"+dto.getGateId()+"' ";
            }else{
                hql +=" "+"where hps_passvehicleinfo.gate_id = '"+dto.getGateId()+"' ";
                flag=true;
            }
        }
        hql+=" GROUP by "
             +" hps_passvehicleinfo.plate_info,hps_passvehicleinfo.gate_id ";

        List<?> list = trafficFlowDao.sqlQueryCount(hql);
        if(list != null && list.size()>0){
            return list.size();
        }
        return 0;       
    }

    /**
     * 写入Excel
     * @param wSheet
     * @param objParams
     * @throws RowsExceededException
     * @throws WriteException
     * @date  2016年6月17日-下午3:06:33
     * @author wangji
     */
    @SuppressWarnings("unchecked")
    public void writeSheet(WritableSheet wSheet, Object... objParams)
            throws RowsExceededException, WriteException {
        List<TrafficFlowInfo> trafficInfoList = (List<TrafficFlowInfo>) objParams[0];
        int col = 0;
        int row = 0;
        WritableFont wf = new WritableFont(WritableFont.TIMES, 12,
                WritableFont.BOLD, false);
        WritableCellFormat wcf = new WritableCellFormat(wf);
        wcf.setAlignment(Alignment.CENTRE);
        wSheet.setColumnView(col++, 10);
        wSheet.setColumnView(col++, 25);
        wSheet.setColumnView(col++, 25);
        wSheet.setColumnView(col++, 10);
        wSheet.setColumnView(col++, 25);
        wSheet.setColumnView(col++, 40);
        col = 0;
        wSheet.addCell(new Label(col++, row, "编号", wcf));
        wSheet.addCell(new Label(col++, row, "车牌号码", wcf));
        wSheet.addCell(new Label(col++, row, "出入口", wcf));
        wSheet.addCell(new Label(col++, row, "通过次数", wcf));
        row++;
        if (trafficInfoList == null || trafficInfoList.size() == 0) {
            return;
        }
        wf = new WritableFont(WritableFont.TIMES, 12, WritableFont.NO_BOLD,
                false);
        wcf = new WritableCellFormat(wf);
        wcf.setAlignment(Alignment.CENTRE);
        int cnt = 0;
        for (TrafficFlowInfo load : trafficInfoList) {
            cnt++;
            col = 0;
            wSheet.addCell(new Label(col++, row, cnt + "", wcf));
            wSheet.addCell(new Label(col++, row, load.getCarNo(), wcf));
            wSheet.addCell(new Label(col++, row, load.getGateName(), wcf));
            wSheet.addCell(new Label(col++, row, load.getPassCount().toString(), wcf));         
            row++;
        }
        return;
    }
    /**
     * 导出所有的信息
     * @param condiction
     * @param orderType
     * @return
     * @date  2016年6月17日-下午3:36:13
     * @author wangji
     */
    public List<TrafficFlowInfo> findAll(TrafficFlowInfoSearchDto condiction,Integer orderType){
          String hqlList = finAllTrafficFlowInfoHql(condiction, orderType);
          List<TrafficFlowInfo> list =trafficFlowDao.sqlQuery(hqlList);
            if(CollectionUtils.isNotEmpty(list)){
                int orderNumber=0;
                for(TrafficFlowInfo Item : list){
                    orderNumber++;
                    GateInfo gateInfo = gateInfoService.fetchGateById(Item.getGateNo());
                    if(gateInfo != null){
                        Item.setGateName(gateInfo.getGateName());//出入口的名称
                    }else{
                        Item.setGateName("");
                    }
                    Item.setOrderNumber(orderNumber);//编号
                }
                 return list;
            }
            return null;
    }
}

4.Action层的操作

package com.hikvision.cms.modules.dataquery.action;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.hikvision.cms.modules.chargemanage.tool.CommonExport;
import com.hikvision.cms.modules.dataquery.domain.TrafficFlowInfo;
import com.hikvision.cms.modules.dataquery.dto.TrafficFlowInfoSearchDto;
import com.hikvision.cms.modules.dataquery.service.impl.TrafficFlowServiceImpl;
import com.hikvision.cms.scaffolding.dao.support.PageBean;
import com.hikvision.cms.util.BaseAction;

@Controller
@Scope(value = "prototype")
/**
 * 车流量信息查询
 * @author wangji
 * @date  2016年6月15日-下午4:22:47
 */
public class TrafficFlowInfoAction extends BaseAction {

    private static final long serialVersionUID = 3519238668079733269L;
    private Logger log = Logger.getLogger(TrafficFlowInfoAction.class);
    private TrafficFlowInfoSearchDto trafficFlowInfoSearchDto;
    public TrafficFlowInfoSearchDto getTrafficFlowInfoSearchDto() {
        return trafficFlowInfoSearchDto;
    }
    public void setTrafficFlowInfoSearchDto(
            TrafficFlowInfoSearchDto trafficFlowInfoSearchDto) {
        this.trafficFlowInfoSearchDto = trafficFlowInfoSearchDto;
    }
    @Resource
    private TrafficFlowServiceImpl trfficService;
    private int pageNo = 1;
    private int pageSize = 50;
    /** 要导出的过车记录id */
    private String exportIds;
    public TrafficFlowServiceImpl getTrfficService() {
        return trfficService;
    }
    public void setTrfficService(TrafficFlowServiceImpl trfficService) {
        this.trfficService = trfficService;
    }
    public int getPageNo() {
        return pageNo;
    }
    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }
    public int getPageSize() {
        return pageSize;
    } 
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public String getExportIds() {
        return exportIds;
    }
    public void setExportIds(String exportIds) {
        this.exportIds = exportIds;
    }
    public PageBean getPageBean() {
        return pageBean;
    }
    public void setPageBean(PageBean pageBean) {
        this.pageBean = pageBean;
    }
    private PageBean pageBean;
    private Integer orderType=-1;

    public Integer getOrderType() {
        return orderType;
    }
    public void setOrderType(Integer orderType) {
        this.orderType = orderType;
    }
    public String searchTrafficFlowInfo(){ 

        try {
            pageBean = trfficService.findPageBean(trafficFlowInfoSearchDto, pageSize, pageNo, orderType);
        } catch (Exception e) {
            // TODO Auto-generated catch block 
            e.printStackTrace();
            log.error("车流量统计信息错误");
        }   
        return "trafficFlowInfoContent";        
    }
    public void exportExcel(){
        try {
            List<TrafficFlowInfo> infoList = trfficService.findAll(trafficFlowInfoSearchDto, orderType);
            if(CollectionUtils.isNotEmpty(infoList)){
                CommonExport.exportExcelWithOneSheet(TrafficFlowServiceImpl.class,
                        getResponse(), "trafficFlowInfo", "车流量统计", infoList);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block 
            e.printStackTrace();
            log.error("车流量统计信息错误");
        }           
    }

}
  1. excel
package com.hikvision.cms.modules.chargemanage.tool;

import java.io.OutputStream;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.log4j.Logger;

import com.hikvision.cms.scaffolding.util.datetime.DateTimeUtil;

/**
 * 通用的导出类
 * 
 * @author chenweiyf2
 * @version v2.0, 13/06/2014
 */
public class CommonExport {
    public static Logger log = Logger.getLogger(CommonExport.class);

    /**
     * @description 导出excel方法,适用于只写sheet1页
     * @author chenweiyf2
     * @date 2014-06-13
     * @param className
     *            Class对象
     * @param response
     *            HttpServletResponse
     * @param fileName
     *            文件名
     * @param sheetName
     *            sheet名
     * @param objParams
     *            参数列表
     * @return void
     */
    public static void exportExcelWithOneSheet(Class className,
            HttpServletResponse response, String fileName, String sheetName,
            Object... objParams) {
        OutputStream out = null;
        WritableWorkbook wbook = null;
        try {
            // 当期日期
            String curDateStr = DateTimeUtil
                    .getCurrentDate("yyyy-MM-dd HH_mm_ss");
            // 获取输出流
            out = response.getOutputStream();
            // 清除首部的空白行
            response.reset();
            String nameContent = "attachment; filename=\"" + fileName
                    + curDateStr + ".xls\"";
            //String header = new String(nameContent.getBytes(), "UTF-8");
            String header = new String(nameContent.getBytes(), "iso8859-1");
            response.setHeader("Content-disposition", header);
            response.setContentType("application/msexcel");

            // 创建工作薄
            wbook = Workbook.createWorkbook(out);

            WritableSheet wSheet = wbook.createSheet(sheetName, 0);

            // 通过反射获取该Class对象的方法集合Method[]
            Method[] methods = className.getMethods();
            for (Method m : methods) {
                // 找到写excel的方法
                if (m.getName().equals("writeSheet")) {
                    // 调用此方法
                    m.invoke(className.newInstance(), wSheet, objParams);
                }
            }

            wbook.write();
            out.flush();
        } catch (Exception e) {
            log.error("导出失败!(" + className.getName() + ")", e);
            throw new RuntimeException();
        } finally {
            try {
                if (null != wbook) {
                    wbook.close();
                }
                if (null != out) {
                    out.close();
                }
            } catch (Exception e) {
                log.error("关闭流资源异常!(" + className.getName() + ")", e);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值