solr search result forwarding entity classes and objects two methods springboot binding assay using solr

Question: is to search out the results from solr turn into an entity class object we want, very common scenario.

1, @Field comment

This property annotation into @Field entity class field [], for example the following

 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 }

 

On access SolrClient can refer to

springboot and use solr binding assay

Use Conversion

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

 

2, a reflection

 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 }

 

Guess you like

Origin www.cnblogs.com/xiaostudy/p/11105277.html