solr搜索结果转实体类对象的两种方法

2023-03-10,,

问题:就是把从solr搜索出来的结果转成我们想要的实体类对象,很常用的情景。

1、使用@Field注解

@Field这个注解放到实体类的属性【字段】中,例如下面

 public class User{
/**
* id
*/
@Field
private String id;
/**
* 用户名
*/
@Field
private String userName;
/**
* 密码
*/
@Field
private String password;
}

关于获取SolrClient可以参考

springboot和solr结合测试使用

使用转换

SolrQuery query = new SolrQuery();
query.setQuery("id:1");// 查询内容,id为1
QueryResponse response = solrClient.query(query);
List<User> beans = response.getBeans(User.class);

2、使用反射

 SolrQuery query = new SolrQuery();
query.setQuery("id:1");// 查询内容,id为1
QueryResponse response = solrClient.query(query);
// 查询结果集
SolrDocumentList results = response.getResults();
List<User> list = new ArrayList();
for(SolrDocument record : records){
User obj = null;
try {
obj = User.class.newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
Field[] fields = User.class.getDeclaredFields();
for(Field field:fields){
Object value = record.get(field.getName());
if(null == value) {
continue;
}
try {
BeanUtils.setProperty(obj, field.getName(), value);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
if(null != obj) {
list.add(obj);
}
}

solr搜索结果转实体类对象的两种方法的相关教程结束。

《solr搜索结果转实体类对象的两种方法.doc》

下载本文的Word格式文档,以方便收藏与打印。