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


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

    1、使用@Field注解

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

     1 public class User{
     2     /**
     3      * id
     4      */
     5     @Field
     6     private String id;
     7     /**
     8      * 用户名
     9      */
    10     @Field
    11     private String userName;
    12         /**
    13      * 密码
    14      */
    15     @Field
    16     private String password;
    17 }

    关于获取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、使用反射

     1 SolrQuery query = new SolrQuery();
     2 query.setQuery("id:1");// 查询内容,id为1
     3 QueryResponse response = solrClient.query(query);
     4 // 查询结果集
     5 SolrDocumentList results = response.getResults();
     6 List<User> list = new ArrayList();
     7 for(SolrDocument record : records){
     8     User obj = null;
     9     try {
    10         obj = User.class.newInstance();
    11     } catch (InstantiationException e1) {
    12         e1.printStackTrace();
    13     } catch (IllegalAccessException e1) {
    14         e1.printStackTrace();
    15     }
    16     Field[] fields = User.class.getDeclaredFields();
    17     for(Field field:fields){
    18         Object value = record.get(field.getName());
    19         if(null == value) {
    20             continue;
    21         }
    22         try {
    23             BeanUtils.setProperty(obj, field.getName(), value);
    24         } catch (IllegalAccessException e) {
    25             e.printStackTrace();
    26         } catch (InvocationTargetException e) {
    27             e.printStackTrace();
    28         }
    29     }
    30     if(null != obj) {
    31         list.add(obj);
    32     }
    33 }
  • 相关阅读:
    SharePoint Forums使用
    使用JS隐藏MOSS菜单
    缓存
    异步委托
    一个层动态放大的例子的一些知识点
    petshop之购物车再思考
    设置防止攻击session(疑惑)
    petshop异步和多线程
    Profile在petshop
    一个简单的显示隐藏知识点
  • 原文地址:https://www.cnblogs.com/xiaostudy/p/11105277.html
Copyright © 2020-2023  润新知