網站首頁 編程語言 正文
前提說明:從solr結果集中取數據,取到了結果集,但是結果集是一個map,而我想要得到的是一個對象,怎么處理呢? 我總計如下三種方法:
第一種:solrDocument中提供了一個獲取每個field對應值的方法,使用此方法獲取所有的field對應的值,set到類中:
功能代碼如下:
private?List?setProductData(SolrDocumentList?list)?{
????????List?datas?=?new?ArrayList();
????????String?jsonStr?=?"";
????????Product?item?=?null;
????????for?(SolrDocument?solrDocument?:?list)?{
????????????item?=?new?Product();
????????????item.setId((Long)solrDocument.getFieldValue("id"));
????????????item.setProduct(solrDocument.getFieldValue("product").toString());
????????????item.setOrderDate((Date)solrDocument.getFieldValue("orderDate"));
????????????...
????????????
????????????datas.add(item);
????????}
????????return?datas;
????}
第二種:使用了BeanUtils工具+反射,通過反射,獲取solrDocument中的所有key和value,然后利用BeanUtils.setProperty(bean, name, value);方法,給Product設置屬性,這樣也有缺點,就是反射過程中容易出現異常,另外更嚴重的是此方法對Date類型的屬性不能處理,而Product中有Date類型的屬性,如果非要使用這種方案,就要寫date類型的轉換類,無疑增加了代碼量。
private?List?setProductData(SolrDocumentList?list)?{
????????List?datas?=?new?ArrayList();
????????String?jsonStr?=?"";
????????Product?item?=?null;
????????for?(SolrDocument?solrDocument?:?list)?{
????????????item?=?new?Product();
Long id =SimpleTypeConverterUtil.convertIfNecessary(solrDocument.getFieldValue("id",Lon.class)
BeanUtils.setProperty(item, "id", id);
String product = SimpleTypeConverterUtil.convertIfNecessary(solrDocument.getFieldValue("product",String.class)
BeanUtils.setProperty(item, "product", product);
Date orderDate = SimpleTypeConverterUtil.convertIfNecessary(solrDocument.getFieldValue("orderDate,Date.class)
BeanUtils.setProperty(item, "orderDate", orderDate);
????????????...
????????????
????????????datas.add(item);
????????}
????????return?datas;
????}
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.SimpleTypeConverter;
import com.zzg.common.convert.DateEditor;
/**
* spring type converter
* @author Administrator
*
*/
public class SimpleTypeConverterUtil {
public static final Logger log = LoggerFactory.getLogger(SimpleTypeConverterUtil.class);
private static final SimpleTypeConverter typeConverterDelegate = new SimpleTypeConverter();
static{
typeConverterDelegate.registerCustomEditor(Date.class, new DateEditor());
}
/**
* @param
* @param value 待轉換值,一般字符串
* @param requiredType 轉后類型類對象
* @return
*/
public static T convertIfNecessary(Object value, Class requiredType) {
T rs = null;
try {
rs = typeConverterDelegate.convertIfNecessary(value, requiredType);
} catch (Exception e) {
log.info(e.getMessage());
if(requiredType == int.class || requiredType == Integer.class){
rs = (T)Integer.valueOf(0);
}
}
return rs;
}
}
package com.zzg.common.convert;
import java.beans.PropertyEditorSupport;
import com.zzg.common.util.DateUtils;
public class DateEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(DateUtils.formatDateStr(text));
}
}
package com.zzg.common.util;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*/
public class DateUtils {
public static final Logger log = LoggerFactory.getLogger(DateUtils.class);
public static final String YYYY = "yyyy" ;
public static final String YYYY_MM = "yyyy-MM" ;
public static final String YYYY_MM_DD = "yyyy-MM-dd" ;
public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss" ;
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss" ;
private static String[] parsePatterns = {
YYYY_MM_DD , YYYY_MM_DD_HH_MM_SS , "yyyy-MM-dd HH:mm" , YYYY_MM ,
"yyyy/MM/dd" , "yyyy/MM/dd HH:mm:ss" , "yyyy/MM/dd HH:mm" , "yyyy/MM" ,
"yyyy.MM.dd" , "yyyy.MM.dd HH:mm:ss" , "yyyy.MM.dd HH:mm" , "yyyy.MM"};
/**
* 獲取當前Date型日期
*
* @return Date() 當前日期
*/
public static Date getNowDate() {
return new Date();
}
/**
* 獲取當前日期, 默認格式為yyyy-MM-dd
*
* @return String
*/
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}
public static final String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date date) {
return parseDateToStr(YYYY_MM_DD, date);
}
public static final String parseDateToStr(final String format, final Date date) {
if (date == null) {
return null;
}
Format formatter = new SimpleDateFormat(format);
return formatter.format(date);
}
/**
* 獲取服務器啟動時間
*/
public static Date getServerStartDate() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
private static final List formarts = new ArrayList<>(5);
static {
formarts.add(new SimpleDateFormat("yyyy-MM"));
formarts.add(new SimpleDateFormat("yyyy-MM-dd"));
formarts.add(new SimpleDateFormat("yyyy-MM-dd hh:mm"));
formarts.add(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
formarts.add(new SimpleDateFormat("yyyy.MM.dd"));
}
public static Date formatDateStr(String source) {
String value = source.trim();
if ("".equals(value)) {
return null;
}
try {
if (source.matches("^\\d{4}-\\d{1,2}$")) {
return formarts.get(0).parse(source);
} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
return formarts.get(1).parse(source);
} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {
return formarts.get(2).parse(source);
} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
return formarts.get(3).parse(source);
} else if (source.matches("^\\d{4}.\\d{1,2}.\\d{1,2}$")) {
return formarts.get(4).parse(source);
} else {
throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
}
} catch (Exception e) {
log.warn("DateUtils.formatDateStr error", e);
return null;
}
}
/**
* 計算兩個時間差
*/
public static String getDatePoor(Date endDate, Date nowDate) {
long nd = (long)1000 * 24 * 60 * 60;
long nh = (long)1000 * 60 * 60;
long nm = (long)1000 * 60;
// 獲得兩個時間的毫秒時間差異
long diff = endDate.getTime() - nowDate.getTime();
// 計算差多少天
long day = diff / nd;
// 計算差多少小時
long hour = diff % nd / nh;
// 計算差多少分鐘
long min = diff % nd % nh / nm;
// 計算差多少秒//輸出結果
return day + "天" + hour + "小時" + min + "分鐘" ;
}
/**
* 增加日期
*
* @param date
* @param field Calendar.MONTH,Calendar.DAY_OF_YEAR
* @param amount 正數為將來時間, 負數為過去時間
* @return
*/
public static Date getAddDate(Date date, int field, int amount) {
Calendar cl = Calendar.getInstance();
cl.setTime(date);
cl.add(field, amount);
Date dateFrom = cl.getTime();
return dateFrom;
}
/**
* 獲取前幾周
*
* @param date
* @return
*/
public static Date getBeforeWeek(Date date, int week) {
return getAddDate(date, Calendar.WEEK_OF_YEAR, week);
}
/**
* 獲取前幾天
*
* @param date
* @return
*/
public static Date getBeforeDay(Date date, int day) {
return getAddDate(date, Calendar.DAY_OF_YEAR, day);
}
/**
* 獲取前幾月
*
* @param date
* @return
*/
public static Date getBeforeMouth(Date date, int mouth) {
return getAddDate(date, Calendar.MONTH, mouth);
}
/**
* 獲取前幾年
*
* @param date
* @return
*/
public static Date getBeforeYear(Date date, int year) {
return getAddDate(date, Calendar.YEAR, year);
}
/**
* 獲取后幾周
*
* @param date
* @return
*/
public static Date getAfterWeek(Date date,int week) {
return getAddDate(date, Calendar.WEEK_OF_YEAR, week);
}
/**
* 獲取后幾天
*
* @param date
* @return
*/
public static Date getAfterDay(Date date, int day) {
return getAddDate(date, Calendar.DAY_OF_YEAR, day);
}
/**
* 獲取后幾月
*
* @param date
* @return
*/
public static Date getAfterMouth(Date date, int month) {
return getAddDate(date, Calendar.MONTH, month);
}
/**
* 獲取后幾年
*
* @param date
* @return
*/
public static Date getAfterYear(Date date, int year) {
return getAddDate(date, Calendar.YEAR, year);
}
}
第三種:先將solrDocument類轉換為json,然后再將此json轉換為我要的業務對象類
/**
*
* @Title: getCommonsHttpSolrServer @Description: HttpSolrClient
* 初始化 @param: @return @param: @throws
* MalformedURLException @return: HttpSolrClient @throws
*/
protected HttpSolrServer getHttpSolrServer(HttpServletRequest request, String solrCoreName) {
String solruri = "http://" + request.getServerName() + ":" + request.getServerPort() + "/solr-webapp/";
solruri = ApplicationPropertiesHolder.getProperty("request.solr.uri", solruri);
solruri = solruri + solrCoreName + "/";
HttpSolrServer server =new HttpSolrServer(solruri);
server.setParser(new XMLResponseParser()); // binary parser is used by
// 設置重試次數
server.setMaxRetries(2);
// 設置超時時間
server.setConnectionTimeout(5000);
return server;
}
// 設置查詢條件
public String getQueryCondition(String text) {
if(StringUtils.isNotEmpty(text)){
StringBuilder builder = new StringBuilder();
List filterStr = Arrays.asList(text.split("\\s+"));
List list = filterStr.stream().map(item ->{
return "text:" + "*".concat(item).concat("*");
}).collect(Collectors.toList());
for (int i = 0; i < list.size(); i++) {
builder.append(list.get(i));
if (i < list.size() - 1) {
builder.append(" and ");
}
}
return builder.toString();
}
return StringUtils.EMPTY;
}
@RequestMapping(value = "/querySolr", method = { RequestMethod.POST })
@ResponseBody
@ApiOperation(value = "工程檔案檢索")
@ApiImplicitParams({
@ApiImplicitParam(name = "text", value = "檢索關鍵字", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "type", value = "檢索類型", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "page", value = "頁碼", required = false, dataType = "Integer", paramType = "query"),
@ApiImplicitParam(name = "limit", value = "頁次", required = false, dataType = "Integer", paramType = "query")
})
public Result querySolr(HttpServletRequest request,
@RequestBody(required = false) HashMap entity) {
String type = SimpleTypeConverterUtil.convertIfNecessary(entity.get("type"), String.class);
entity.remove("type");
if(StringUtils.isEmpty(type)){
return Result.error("檢索必須指定類型");
}
// 構建查詢條件
SolrQuery query = new SolrQuery();
// 分頁參數
PageParam rb = super.initPageBounds(entity);
query.setStart((rb.getPageNo() - 1) * rb.getLimit() > 0
? (rb.getPageNo() - 1) * rb.getLimit() : 0);
query.setRows(rb.getLimit());
// 設置查詢條件
String condition = this.getQueryCondition(SimpleTypeConverterUtil.convertIfNecessary(entity.get("text"), String.class));
if (StringUtils.isNotEmpty(condition)) {
logger.error("query 條件:" + condition);
query.setQuery(condition);
}
// solr 查詢
QueryResponse queryResponse = null;
try {
HttpSolrServer httpSolrServer = this.getHttpSolrServer(request, type);
queryResponse = httpSolrServer.query(query);
} catch (SolrServerException e) {
// TODO Auto-generated catch block
logger.error("solr 檢索異常:{}", e.getMessage(), e);
return Result.error("檔案檢索異常");
}
// solr 查詢結果分頁
List list = queryResponse.getResults();
if(CollectionUtils.isEmpty(list)){
return Result.error("檔案未檢索到相關數據");
}
PageData
原文鏈接:https://blog.csdn.net/zhouzhiwengang/article/details/123519693
相關推薦
- 2022-09-16 Python?docx庫刪除復制paragraph及行高設置圖片插入示例_python
- 2022-05-22 關于VS2022不能使用<bits/stdc++.h>的解決方案(萬能頭文件)_C 語言
- 2022-10-13 Windows?Server2012?R2?FTP服務器配置圖文教程_FTP服務器
- 2023-05-20 linux?shell輸出換行簡單實例_linux shell
- 2022-03-30 Docker搭建RabbitMQ集群的方法步驟_docker
- 2023-02-02 C++實現延遲的方法詳解_C 語言
- 2022-09-15 Python移動測試開發subprocess模塊項目實戰_python
- 2022-06-14 nginx搭建NFS服務器的方法步驟_nginx
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支