首页 > 数据库技术 > 详细

Spring Data JPA原生SQL查询

时间:2017-09-11 22:14:21      阅读:1206      评论:0      收藏:0      [点我收藏+]
package com.wanda.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();
}

}

Spring Data JPA原生SQL查询

原文:http://www.cnblogs.com/lchb/p/7506944.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!