zoukankan      html  css  js  c++  java
  • Spring Data JPA原生SQL查询

    package com.test.cms.dao.repository;
    import org.springframework.stereotype.Repository;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    import java.math.BigInteger;
    import java.util.*;

    /**
    * 构建复杂查询
    * @author lchb
    */
    @Repository
    public class NativeQueryRepository{

    @PersistenceContext
    private EntityManager entityManager;

    /**
    * 根据sql查询
    * @param sql
    * @param resultClass
    * @param <T>
    * @return
    */
    public <T> List<T> findBySql(String sql,Class resultClass){
    Query nativeQuery=null;
    if(resultClass!=null && !resultClass.equals(Object.class)) {
    nativeQuery = entityManager.createNativeQuery(sql, resultClass);
    }else{
    nativeQuery = entityManager.createNativeQuery(sql);
    }

    List rows = nativeQuery.getResultList();
    List<T> resultList=new ArrayList<T>();
    for (Object obj : rows) {
    T row=(T)obj;
    resultList.add(row);
    }
    return resultList;
    }

    /**
    * 根据参数查询
    * @param sql
    * @param parameters
    * @param resultClass
    * @param <T>
    * @return
    */
    public <T> List<T> findBySql(String sql,Map<String,Object> parameters,Class resultClass){
    Query nativeQuery=null;
    if(resultClass!=null && !resultClass.equals(Object.class)) {
    nativeQuery = entityManager.createNativeQuery(sql, resultClass);
    }else{
    nativeQuery = entityManager.createNativeQuery(sql);
    }

    Iterator<Map.Entry<String,Object>> entries = parameters.entrySet().iterator();
    while (entries.hasNext()) {
    Map.Entry<String,Object> entry = entries.next();
    nativeQuery.setParameter(entry.getKey(),entry.getValue());
    }

    List rows = nativeQuery.getResultList();
    List<T> resultList=new ArrayList<T>();
    for (Object obj : rows) {
    T row=(T)obj;
    resultList.add(row);
    }
    return resultList;
    }


    public Integer findCountBySql(String sql,Map<String,Object> parameters){
    List<Object> list=this.findBySql(sql,parameters,Object.class);
    BigInteger total=(BigInteger)list.get(0);
    return total.intValue();
    }

    }
  • 相关阅读:
    java、maven环境搭建
    httpclient的get和post
    使用批处理命令定期清理删除指定后缀文件,释放空间
    WebService—规范介绍和几种实现WebService的框架介绍
    Delphi7 ADO面板上的控件简介
    sqlserver中判断表或临时表是否存在
    Delphi中Format与FormatDateTime函数详解
    delphi弹出信息框大全
    Delphi 日期时间函数
    Delphi7数据库编程之TDataSet(转)
  • 原文地址:https://www.cnblogs.com/lchb/p/7506944.html
Copyright © 2011-2022 走看看