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

简介: 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.spring


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;
}
    
}
目录
相关文章
|
16天前
|
SQL 存储 人工智能
Vanna:开源 AI 检索生成框架,自动生成精确的 SQL 查询
Vanna 是一个开源的 Python RAG(Retrieval-Augmented Generation)框架,能够基于大型语言模型(LLMs)为数据库生成精确的 SQL 查询。Vanna 支持多种 LLMs、向量数据库和 SQL 数据库,提供高准确性查询,同时确保数据库内容安全私密,不外泄。
83 7
Vanna:开源 AI 检索生成框架,自动生成精确的 SQL 查询
|
23天前
|
SQL Java
使用java在未知表字段情况下通过sql查询信息
使用java在未知表字段情况下通过sql查询信息
34 8
|
1月前
|
SQL 安全 PHP
PHP开发中防止SQL注入的方法,包括使用参数化查询、对用户输入进行过滤和验证、使用安全的框架和库等,旨在帮助开发者有效应对SQL注入这一常见安全威胁,保障应用安全
本文深入探讨了PHP开发中防止SQL注入的方法,包括使用参数化查询、对用户输入进行过滤和验证、使用安全的框架和库等,旨在帮助开发者有效应对SQL注入这一常见安全威胁,保障应用安全。
53 4
|
1月前
|
SQL 监控 关系型数据库
SQL语句当前及历史信息查询-performance schema的使用
本文介绍了如何使用MySQL的Performance Schema来获取SQL语句的当前和历史执行信息。Performance Schema默认在MySQL 8.0中启用,可以通过查询相关表来获取详细的SQL执行信息,包括当前执行的SQL、历史执行记录和统计汇总信息,从而快速定位和解决性能瓶颈。
|
7月前
|
SQL 缓存 Java
框架分析(9)-Hibernate
框架分析(9)-Hibernate
|
1月前
|
缓存 Java 数据库连接
Hibernate:Java持久层框架的高效应用
通过上述步骤,可以在Java项目中高效应用Hibernate框架,实现对关系数据库的透明持久化管理。Hibernate提供的强大功能和灵活配置,使得开发者能够专注于业务逻辑的实现,而不必过多关注底层数据库操作。
18 1
|
4月前
|
SQL Java 数据库连接
Hibernate 是一款开源 ORM(对象关系映射)框架,封装了 JDBC,允许以面向对象的方式操作数据库,简化了数据访问层的开发。
Hibernate 是一款开源 ORM(对象关系映射)框架,封装了 JDBC,允许以面向对象的方式操作数据库,简化了数据访问层的开发。通过映射机制,它可以自动处理对象与数据库表之间的转换,支持主流数据库,提高了代码的可移植性和可维护性。其核心接口包括 SessionFactory、Session 和 Transaction 等,通过它们可以执行数据库的 CRUD 操作。配置方面,需在项目中引入 Hibernate 及数据库驱动依赖,并创建 `hibernate.cfg.xml` 配置文件来设置数据库连接和 Hibernate 行为参数。
60 1
|
4月前
|
数据库 Java 数据库连接
Struts 2 与 Hibernate 的完美邂逅:如何无缝集成两大框架,轻松玩转高效 CRUD 操作?
【8月更文挑战第31天】本文通过具体示例介绍了如何在 Struts 2 中整合 Hibernate,实现基本的 CRUD 操作。首先创建 Maven 项目并添加相关依赖,接着配置 Hibernate 并定义实体类及其映射文件。然后创建 DAO 接口及实现类处理数据库操作,再通过 Struts 2 的 Action 类处理用户请求。最后配置 `struts.xml` 文件并创建 JSP 页面展示用户列表及编辑表单。此示例展示了如何配置和使用这两个框架,使代码更加模块化和可维护。
142 0
|
5月前
|
SQL Java 数据库连接
Java面试题:简述ORM框架(如Hibernate、MyBatis)的工作原理及其优缺点。
Java面试题:简述ORM框架(如Hibernate、MyBatis)的工作原理及其优缺点。
90 0
|
6月前
|
Java 数据库连接 数据库
探索JPA生态:Hibernate与其他ORM框架的对比分析
【6月更文挑战第25天】**JPA标准下的Hibernate是流行的ORM实现,提供丰富功能如二级缓存和延迟加载,但其学习曲线较陡,性能优化复杂。相比如MyBatis,Hibernate的JPQL更面向对象,MyBatis则接近SQL。选择ORM需考虑项目需求和个人偏好。**
98 0
下一篇
DataWorks