package com.ucap.netcheck.dao.impl;

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

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ucap.netcheck.combination.beans.MainPageResultCombinationBean;
import com.ucap.netcheck.common.Page;
import com.ucap.netcheck.common.dao.BaseDAO;
import com.ucap.netcheck.dao.ISingleRejectDao;
import com.ucap.netcheck.entity.MainPageScanFail;
import com.ucap.netcheck.entity.MainPageScanResult;
import com.ucap.netcheck.exception.DAOException;

/**
 * @Title: CheckMainPageResultDaoImpl.java
 * @Package com.ucap.netcheck.dao.impl
 * @Description:
 * @author
 * @date 2015-4-8 下午5:04:34
 * @version V1.0
 */
@Repository
@Transactional
public class SingleRejectDaoImpl extends BaseDAO implements ISingleRejectDao {

@Autowired
 private SessionFactory sessionFactory;
 
 @SuppressWarnings("unchecked")
 public MainPageScanResult queryMainPageScanResultUnique(Object... params) {
  try {
   String sql = "FROM MainPageScanResult m "
     + "WHERE m.errorPercent > 5.0 " + "and m.innerUUID =? "
     + "and m.taskId =? ";
   Session session = sessionFactory.getCurrentSession();
   
   List<MainPageScanResult> list = session.createQuery(sql)
        .setParameter(0,(String)params[0])
        .setParameter(1,(Integer)params[1])
        .list();
   
   if (!list.isEmpty()) {
    return list.get(0);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }
 
  /**
   * queryMainPageScanFailById(通过这个方法实现查找首页扫描失败的结果)
   *
   * @Title: queryMainPageScanFailById
   * @Description:
   * @param @param pageNo
   * @param @param pageRow
   * @param @param id
   * @param @return    设定文件
   * @return Page    返回类型
   * @throws
   */
 public Page queryMainPageScanFailById(int pageNo, int pageRow,Integer id) {
  try {
   List<Object> params = new ArrayList<Object>();
   
   String hql = "FROM MainPageScanFail m WHERE m.mainPageScanId = ? ";
   
   params.add(id);
   
   Page page = this.queryByPage(hql, pageNo, pageRow, params);
   return page;
  } catch (Exception e) {
   throw new DAOException("分页查询所有->ERROR", e);
  }
 }
 
 @SuppressWarnings("unchecked")
 public List<MainPageScanFail> queryMainPageScanFailListById(Integer id) {
  try {
   String hql = "FROM MainPageScanFail m WHERE m.mainPageScanId =:mainPageScanId ";
   
   List<MainPageScanFail> list = sessionFactory.getCurrentSession()
    .createQuery(hql)
    .setParameter("mainPageScanId", id)
    .list();
   
   return list;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

/**
  * queryMainPageScaneResultStatistics(这个方法实现对这个表的信息进行统计)
  *
  * @Title: queryMainPageScaneResultStatistics
  * @Description: 这个方法实现对这个表的信息进行统计
  * @param @param objs
  * @param @return 设定文件
  * @return Page<MainPageScanResult> 返回类型
  * @throws
  */
 @SuppressWarnings("unchecked")
 public MainPageResultCombinationBean queryMainPageScaneResultStatistics(
   Object... objs) {
  try {
   String hql = "SELECT new com.ucap.netcheck.combination.beans.MainPageResultCombinationBean("
     + " min(m.taskStartTime),max(m.taskEndTime),count(m.innerUUID),max(m.totalScanNum),max(m.failNum)) "
     + " FROM "
     + MainPageScanResult.class.getSimpleName()
     + " m WHERE m.innerUUID = ? " + " AND m.taskId = ? ";

List<MainPageResultCombinationBean> list = sessionFactory
     .getCurrentSession().createQuery(hql)
     .setParameter(0, (String) objs[0]).setParameter(1, objs[1])
     .list();
   return (!list.isEmpty() ? (MainPageResultCombinationBean) list
     .get(0) : null);
  } catch (Exception e) {
   throw new DAOException("分页查询所有->ERROR", e);
  }
 }

@SuppressWarnings({ "rawtypes", "unchecked"})
 @Override
 public Page queryMainPageUpdateResultByPage(int pageNo, int pageRow,
   Object... objs) {
  try {
   StringBuilder sql = new StringBuilder(
       "SELECT " +
       "cm.id AS id," +
       "cm.TASK_Id AS taskId," +
       "cm.innerUUID AS innerUUID," +
       "cm.checkSysTaskId AS checkSysTaskId," +
          "cm.URL AS URL," +
          "cm.first_channel AS firstChannel," +
          "cm.second_channel AS secondChannel," +
          "cm.chanel_name AS chanelName," +
          "cm.TITLE AS title," +
          "cm.IMG_Url AS imgURL," +
          "cm.lastModifyTime AS lastModifyTime, " +
          "cm.SHOW_TIME AS showTime," +
          "cm.scanTime AS scanTime," +
          "cm.isReject AS isReject " +
    "FROM cpu_mp AS cm " +
    "WHERE cm.innerUUID =? " +
    "AND cm.TASK_ID =? " +
    "AND cm.isReject = 1 "
   );
   
   Query query = sessionFactory
     .getCurrentSession()
     .createSQLQuery(sql.toString())
     .setParameter(0, (String) objs[0])
     .setParameter(1, (Integer)objs[1]);

Page page = new Page();
            page.setPageNum(pageNo);
            page.setNumPerPage(pageRow);
            page.setAllRows(query.list().size());
           
            int allPages = page.getAllRows() / page.getNumPerPage();
   if (page.getAllRows() % page.getNumPerPage() == 0) {
    page.setAllPages(allPages); // 总页数
   } else {
    page.setAllPages(allPages + 1); // 总页数
   }
           
            query.setFirstResult((pageNo - 1) * pageRow);
            query.setMaxResults(pageRow);
            //集合
            List<Object[]> list = query.list();
            page.setRecordList(list);
           
            return page;
  } catch (Exception e) {
   throw new DAOException("分页查询所有->ERROR", e);
  }
 }
 
 @SuppressWarnings({"unchecked"})
 @Override
 public List<Object[]> queryMainPageUpdateResultByCondition(Object... objs) {
  try {
   StringBuilder sql = new StringBuilder(
       "SELECT " +
       "cm.id AS id," +
       "cm.TASK_Id AS taskId," +
       "cm.innerUUID AS innerUUID," +
       "cm.checkSysTaskId AS checkSysTaskId," +
          "cm.URL AS URL," +
          "cm.first_channel AS firstChannel," +
          "cm.second_channel AS secondChannel," +
          "cm.chanel_name AS chanelName," +
          "cm.TITLE AS title," +
          "cm.IMG_Url AS imgURL," +
          "cm.lastModifyTime AS lastModifyTime, " +
          "cm.SHOW_TIME AS showTime," +
          "cm.scanTime AS scanTime," +
          "cm.isReject AS isReject " +
    "FROM cpu_mp AS cm " +
    "WHERE cm.innerUUID =? " +
    "AND cm.TASK_ID =? " +
    "AND cm.isReject = 1 "
   );
   
   Query query = sessionFactory
     .getCurrentSession()
     .createSQLQuery(sql.toString())
     .setParameter(0, (String) objs[0])
     .setParameter(1, (Integer)objs[1]);

//集合
            List<Object[]> list = query.list();
            return list;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

}

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

通过SQL将查询的结果返回到一个Bean中

@SuppressWarnings({ "unchecked" })
 @Override
 @Transactional(propagation = Propagation.REQUIRED)
 public Page<CommunityActivity> queryJoinedActivity(int pageNo, int pageRow,
   int userId) {
  // 分页实体
  Page<CommunityActivity> page = new Page<CommunityActivity>();
  try {
   page.setPageNum(pageNo);
   page.setNumPerPage(pageRow);
   Session session = sessionFactory.getCurrentSession();
   String sql = "select ac.* from dm_commuinty_activity"
     + " ac where ac.id in(select t.activity_id from DM_ACTIVITY_USER t "
     + " where t.user_id = " + userId + ")";

// 查询
   Query query = session.createSQLQuery(sql).addEntity(
     CommunityActivity.class);

// 总记录数
   page.setAllRows(query.list().size());
   // page.setAllRows(((Number) query.uniqueResult()).intValue());

query.setFirstResult((pageNo - 1) * pageRow);
   query.setMaxResults(pageRow);
   // 集合
   page.setRecordList(query.list());

int allPages = page.getAllRows() / page.getNumPerPage();
   if (page.getAllRows() % page.getNumPerPage() == 0) {
    page.setAllPages(allPages); // 总页数
   } else {
    page.setAllPages(allPages + 1); // 总页数
   }
  } catch (Exception ex) {
   throw new DAOException("分页查询所有->ERROR", ex);
  }
  return page;
 }
===========================

查询不同表中内容,并将查到的不同表中的内容放到List中

@Override
 @Transactional(propagation = Propagation.REQUIRED)
 public List getAttrAndDeadResult(int taskId, int targetID) {
  Session session = sessionFactory.getCurrentSession();
//  String sql = "select d.depth, p.imgUrl, d.point, d.scanTime, "
//    + "d.title, d.url, p.parentTitle, p.parentUrl,d.id,d.urlType,d.code "
//    + "from deadurlresult d, checkresult c, deadurl_parent_info p "
//    + "where d.taskId=c.taskId and d.id=p.deadId and d.taskId=:tid and c.targetId=:tgID "
//    + "and (d.urlType=0 or d.urlType=1 or d.urlType=2 or d.urlType=3 "
//    + "or d.urlType=4 or d.urlType=7 or d.urlType=8) ";
  
  String sql = "SELECT d.depth, p.imgUrl, d.point, d.scanTime, d.title, d.url, p.parentTitle, p.parentUrl,d.id,d.urlType,d.code " +
      "FROM " +
      "(SELECT * FROM deadurlresult  c WHERE " +
      "c.taskId=:tid " +
      "AND (c.urlType=0 OR c.urlType=1 OR c.urlType=2 OR c.urlType=3 " +
      "OR c.urlType=4 OR c.urlType=7 OR c.urlType=8)" +
      ") d LEFT JOIN  deadurl_parent_info p ON  d.id=p.deadId";
  
  Query sqlQuery = session.createSQLQuery(sql);
  sqlQuery.setParameter("tid", taskId);
  //sqlQuery.setParameter("tgID", targetID);
  return sqlQuery.list();
 }

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

/**
  * 通过这方法实现爆粗广告日志信息
  */
 @Transactional(propagation = Propagation.REQUIRED)
 public List<AdvertiseStatisticResult> gainStatisticResult(Integer adPageId,
   Date startDate, Date endDate) {
  try {
   List<AdvertiseStatisticResult> dataResults = new ArrayList<AdvertiseStatisticResult>();
   
   String sql = "select t2.ad_position_name,count(t.AD_POS_ID) " +
       "from DM_ADVERTISE_ACCESS_LOG t,Dm_Advertise_Position t2 " +
       "WHERE t.adpageid = ? " +
       "AND t2.id = t.ad_pos_id " +
       "group by t2.ad_position_name,t.ad_pos_id";
   
   List list = sessionFactory.getCurrentSession().createSQLQuery(sql)
     .setParameter(0, adPageId)
     //.setParameter(1, startDate)
     //.setParameter(2, endDate)
     .list();
   
   if (!list.isEmpty()) {
    for (int i = 0; i < list.size(); i++) {
     AdvertiseStatisticResult asr = new AdvertiseStatisticResult();
     asr.setName((String)((Object[])list.get(i))[0]);
     asr.setY(Integer.valueOf((((Object[])list.get(i))[1]).toString()).intValue());     //这里的Y是int类型的,这里不能直接通过(Integer)的方式进行强制转换得到,否则出现

//java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Integer
     
     dataResults.add(asr);
    }
   }
   
   return dataResults;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

==========================================================================================================
查询的内容转成制定的实体:
// 附件
@Override
@Transactional(propagation = Propagation.REQUIRED)
public List<AffixBean> getAffix() {
Session session = sessionFactory.getCurrentSession();
String hql = "select a.nrid,a.file_type,a.file_path,a.file_name from dm_affix a";
Query query = session.createSQLQuery(hql)
.addScalar("nrid", StandardBasicTypes.INTEGER)
.addScalar("file_type", StandardBasicTypes.STRING)
.addScalar("file_path", StandardBasicTypes.STRING)
.addScalar("file_name", StandardBasicTypes.STRING)
.setResultTransformer(Transformers.aliasToBean(AffixBean.class));
List<AffixBean> list = query.list();
return list;
}

//AffixBean的内容如下:
package com.kuman.cartoon.common.bean;

public class AffixBean {
/**
* 内容ID
*/
private Integer nrid;
/**
     * 文件路径
     */
    private String file_path;
    
    /**
     * 文件类型
     */
    private String file_type;
    
    /**
     * 文件名
     */
    private String file_name;

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_type() {
return file_type;
}

public void setFile_type(String file_type) {
this.file_type = file_type;
}

public String getFile_name() {
return file_name;
}

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

Hibernate查询之SQL查询,查询结果用new新对象的方式接受,hql查询,通过SQL查询的结果返回到一个实体中,查询不同表中内容,并将查到的不同表中的内容放到List中的更多相关文章

  1. 5) ModelSerializer(重点) 基表 测试脚本 多表关系建外键 正反查 级联 插拔式连表 序列化反序列化整合 增删查 封装response

    一.前戏要做好 配置:settings.py #注册drf INSTALLED_APPS = [ # ... 'api.apps.ApiConfig', 'rest_framework', ] ​ # ...

  2. EF Database first 中,实现 多个表对应一个 实体的 查询

    1.首先 创建好 数据 库. hobby表 major 表 student 表 外键 关系如下 2. 实现将 数据库 映射到EDM中 视图如下 在VS中 生成了 3个实体类  ,对应的是 数据库中的3 ...

  3. Sql Server的艺术(六) SQL 子查询,创建使用返回多行的子查询,子查询创建视图

    子查询或内部查询或嵌套查询在另一个SQL查询的查询和嵌入式WHERE子句中. 子查询用于返回将被用于在主查询作为条件的数据,以进一步限制要检索的数据. 子查询可以在SELECT,INSERT,UPDA ...

  4. hibernate 联合主键生成机制(组合主键XML配置方式)

    hibernate 联合主键生成机制(组合主键XML配置方式)   如果数据库中用多个字段而不仅仅是一个字段作为主键,也就是联合主键,这个时候就可以使用hibernate提供的联合主键生成策略. 具体 ...

  5. hibernate(七) hibernate中查询方式详解

    序言 之前对hibernate中的查询总是搞混淆,不明白里面具体有哪些东西.就是因为缺少总结.在看这篇文章之前,你应该知道的是数据库的一些查询操作,多表查询等,如果不明白,可以先去看一下 MySQL数 ...

  6. Hibernate 检索查询的几种方式(HQL,QBC,本地SQL,集成Spring等)

    1.非集成Spring hibernate的检索方式,主要有以下五种. 1.导航对象图检索方式.(根据已经加载的对象,导航到其他对象.) 2.OID检索方式.(按照对象的OID来检索对象.) 3.HQ ...

  7. Hibernate学习(七)———— hibernate中查询方式详解

    序言 之前对hibernate中的查询总是搞混淆,不明白里面具体有哪些东西.就是因为缺少总结.在看这篇文章之前,你应该知道的是数据库的一些查询操作,多表查询等 --WH 一.hibernate中的5种 ...

  8. Sql Server中查询今天、昨天、本周、上周、本月、上月数据

    Sql Server中查询今天.昨天.本周.上周.本月.上月数据 在做Sql Server开发的时候有时需要获取表中今天.昨天.本周.上周.本月.上月等数据,这时候就需要使用DATEDIFF()函数及 ...

  9. 如何查找MySQL中查询慢的SQL语句

    如何查找MySQL中查询慢的SQL语句 更多 如何在mysql查找效率慢的SQL语句呢?这可能是困然很多人的一个问题,MySQL通过慢查询日志定位那些执行效率较低的SQL 语句,用--log-slow ...

随机推荐

  1. C++中的各种可调用对象

    概述 一组执行任务的语句都可以视为一个函数,一个可调用对象.在程序设计的过程中,我们习惯于把那些具有复用性的一组语句抽象为函数,把变化的部分抽象为函数的参数. 函数的使用能够极大的极少代码重复率,提高 ...

  2. left join 连表时,on后多条件无效问题

    http://www.cnblogs.com/guixiaoming/p/6516261.html left join 连表时,on后多条件无效问题 最近开发素材库项目,各种关系复杂的表,一度6张表的 ...

  3. asp.net用户控件引用

    <%@ Register Src="~/_module/IndexChannelHead.ascx" TagName="tn" TagPrefix=&qu ...

  4. 利用Express和ejs编写简单页面

    1.创建临时文件夹ejsdemo $ mkdir ejsdemo 2.进入ejsdemo 初始化项目 $ npm init 3.安装express $ npm install express --sa ...

  5. Ubuntu 16.04+.Net Core+Docker+Uginx安装部署

    前言 最近公司的项目打算移植到.Net Core平台,所以调研了一下.Net Core在Linux下的安装部署.本篇文章会一步步的描述从安装到配置到部署的全部过程.在文章的结构和内容里,笔者借鉴了很多 ...

  6. 各种异常 及异常类和Object类

    Day05 异常 Object类 equals方法,用于比较两个对象是否相同,它其实就是使用两个对象的内存地址在比较.Object类中的equals方法内部使用的就是==比较运算符. 2. 描述人这个 ...

  7. POJ 2135 最小费用最大流

    题目链接 Farm Tour Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 18961   Accepted: 7326 D ...

  8. Codeforces Round #305 (Div. 2) B. Mike and Fun 暴力

     B. Mike and Fun Time Limit: 20 Sec  Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/548/pro ...

  9. Docker配置 DNS

    Docker 没有为每个容器专门定制镜像,那么怎么自定义配置容器的主机名和 DNS 配置呢? 秘诀就是它利用虚拟文件来挂载到来容器的 3 个相关配置文件. 在容器中使用 mount 命令可以看到挂载信 ...

  10. springMVC源码解析--ViewResolver视图解析器执行(三)

    之前两篇博客springMVC源码分析--ViewResolver视图解析器(一)和springMVC源码解析--ViewResolverComposite视图解析器集合(二)中我们已经简单介绍了一些 ...