BindingException:Could not instantiate object of class com.sa.pojo.Person

Person:

package com.sa.pojo;

import org.apache.solr.client.solrj.beans.Field;

public class Person {
    @Field
    private String id;
    @Field
    private String name;
    @Field
    private Integer age;
    @Field
    private String addr;

    public Person() {
    }

    public Person(String id, String name, int age, String addr) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.addr = addr;
    }

    public String getId() {
        return id;
    }
    //@Field
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    //@Field
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }
    //@Field
    public void setAge(int age) {
        this.age = age;
    }

    public String getAddr() {
        return addr;
    }
    //@Field
    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", addr='" + addr + '\'' +
                '}';
    }
}

SolrTest:

package com.sa.solr;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import com.sa.pojo.Person;
import org.apache.solr.client.solrj.SolrQuery;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.beans.Field;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Collation;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Correction;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

public class SolrTest {

    /**
     * solr http服务地址
     */
    public static String SOLR_URL;

    /**
     * solr的core
     */
    public static String SOLR_CORE;

    static {
//        Properties properties = new Properties();
//        String path = SolrMain.class.getResource("/").getFile().toString()
//                + "solr.properties";
//        try {
//            FileInputStream fis = new FileInputStream(new File(path));
//            properties.load(fis);
//            SOLR_URL = properties.getProperty("SOLR_URL");
//            SOLR_CORE = properties.getProperty("SOLR_CORE");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        SOLR_URL = "http://127.0.0.1:8080/solr/";
        SOLR_CORE = "core1";
    }

    /**
     * 主函数入口
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        //getSolrClient();
        // 1.测试插入文档
//        Map<String, String> map = new HashMap<String, String>();
//        map.put("id", "00002");
//        map.put("name", "zhangsan");
//        map.put("age", "25");
//        map.put("addr", "深圳");
//        addDocument(map);

        // 2.通过bean添加document
//        List<Person> persons = new ArrayList<Person>();
//        persons.add(new Person("00002", "lisi", 25, "重庆"));
//        persons.add(new Person("00003", "wangwu", 26, "上海"));
//        addDocumentByBean(persons);


//
//        // 3.根据id集合删除索引
//        List<String> ids = new ArrayList<String>();
//        ids.add("00001");
//        ids.add("00002");
//        ids.add("00003");
//        ids.add("00004");
//        deleteDocumentByIds(ids);
//
//        // 4.查询
        getDocument();
//
//        // 5.spell测试
        //getSpell();

        //6
      //  addBean();


        //7批量加入bean
       // multyAddBean();

    }

    /**
     * 批量加入bean
     */
    private static void multyAddBean() throws Exception {
        //[1]获取连接
        HttpSolrClient solrClient = getSolrClient();
        //[3]创建对象
        for(int i=20;i<30;i++){
            Person person=new Person(String.valueOf(i), "wangwu", i, "杭州");
            //[4]添加对象
            solrClient.addBean(person);
        }

        //[5]提交操作
        commitAndCloseSolr(solrClient);
    }


    /**
     * 创建SolrServer对象
     *
     * 该对象有两个可以使用,都是线程安全的
     * 1、CommonsHttpSolrServer:启动web服务器使用的,通过http请求的
     * 2、 EmbeddedSolrServer:内嵌式的,导入solr的jar包就可以使用了
     * 3、solr 4.0之后好像添加了不少东西,其中CommonsHttpSolrServer这个类改名为HttpSolrClient
     *  注意:solr5以后URL指向自定义核心的名称,如实例名称是core1,那么URL为http://127.0.0.1:8080/solr/core1
     *
     * @return
     */
    public static HttpSolrClient getSolrClient(){
        HttpSolrClient solr = null;
        solr = new HttpSolrClient.Builder(SOLR_URL+SOLR_CORE).withConnectionTimeout(10000).withSocketTimeout(60000).build();
        return solr;
    }

    /**
     * 添加文档
     *
     * @param map
     * @throws Exception
     */
    private static void addDocument(Map<String, String> map)
            throws Exception {
        SolrInputDocument sid = new SolrInputDocument();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sid.addField(entry.getKey(), entry.getValue());
        }
        HttpSolrClient solrClient = getSolrClient();
        solrClient.add(sid);
        commitAndCloseSolr(solrClient);
    }

    /**
     * 添加文档,通过bean方式
     *
     * @param persons
     * @throws Exception
     */
    private static void addDocumentByBean(List<Person> persons)
            throws Exception {
        HttpSolrClient solrClient = getSolrClient();
        solrClient.addBeans(persons);
        commitAndCloseSolr(solrClient);
    }

      /**
     * 6、Java对象绑定,通过对象创建索引
     */
    public static void addBean() throws Exception{
        //[1]获取连接
        HttpSolrClient solrClient = getSolrClient();
        //[3]创建对象
        Person person=new Person("00004", "lisi", 25, "重庆");
        //[4]添加对象
        solrClient.addBean(person);
        //[5]提交操作
        commitAndCloseSolr(solrClient);
    }

    /**
     * 根据id集合删除索引
     *
     * @param ids
     * @throws Exception
     */
    private static void deleteDocumentByIds(List<String> ids)
            throws Exception {
        HttpSolrClient solrClient = getSolrClient();
        solrClient.deleteById(ids);
        commitAndCloseSolr(solrClient);
    }

    /**
     * 8、通过deleteByQuery删除索引
     */
    public void deleteBean() throws Exception{
        //[1]获取连接
        HttpSolrClient solrClient = getSolrClient();
        //[2]执行删除
        solrClient.deleteByQuery("id:100");
        //[3]提交操作  关闭资源
        commitAndCloseSolr(solrClient);
    }
    /**
     * SolrParams 有一个 SolrQuery 子类,它提供了一些方法极大地简化了查询操作。下面是 SolrQuery示例代码
     * @throws Exception
     */

    private static void getDocument() throws Exception {
        HttpSolrClient solrClient = getSolrClient();
        SolrQuery sq = new SolrQuery();

        // q查询
        //sq.set("q", "addr:杭州");//精确检索 返回指定值
        //排除查询也就是我们在数据库和程序中经常处理的不等于,solr的语法是在定语前加【-】
        //例如:  -id:[20 TO 25]   -*:*
        //sq.set("q", "name:wangwu");  //返回所有值
        //sq.set("q","addr:杭州");
        sq.set("q","*:*");
        // filter查询  filter查询必须和query(q查询)配合使用
        //sq.addFilterQuery("id:[0 TO 30]");

        //添加需要回显得内容
        sq.addField("id");
        sq.addField("name");
        sq.addField("age");
        sq.addField("addr");

        // 排序
        sq.setSort("id", SolrQuery.ORDER.asc);

        // 分页 从第0条开始取,取一条
        sq.setStart(0);
        //sq.setRows(1);

        //设置每页显示多少条,如果不设置默认查出符合条件的所有
        //sq.setRows(2);
        // 设置高亮
        sq.setHighlight(true);

        // 设置高亮的字段
        sq.addHighlightField("name");

        // 设置高亮的样式
        sq.setHighlightSimplePre("<font color='red'>");
        sq.setHighlightSimplePost("</font>");

        QueryResponse result = solrClient.query(sq);

        // 这里可以从result获得查询数据(两种方式如下)

        // 1.获取document数据
        System.out.println("1.获取document数据-------------------------");
        SolrDocumentList results = result.getResults();
        // 获取查询的条数
        System.out.println("一共查询到" + results.getNumFound() + "条记录");
        for (SolrDocument solrDocument : results) {
            System.out.println("id:" + solrDocument.get("id"));
            System.out.println("name:" + solrDocument.get("name"));
            System.out.println("age:" + solrDocument.get("age"));
            System.out.println("addr:" + solrDocument.get("addr"));
        }

        // 2.获取对象信息,需要传入对应对象的类class
        System.out.println("2.获取对象信息,需要传入对应对象的类class-----------");
        List<Person> persons = result.getBeans(Person.class);
        System.out.println("一共查询到" + persons.size() + "条记录");
        for (Person person : persons) {
            System.out.println(person.toString());
        }
        commitAndCloseSolr(solrClient);
    }

    /**
     * 查询使用spell接口,输入错误,solr可以给出建议词
     *
     * @throws Exception
     */
    private static void getSpell() throws Exception {
        HttpSolrClient solrClient = getSolrClient();
        SolrQuery sq = new SolrQuery();
        sq.set("qt", "/spell");

        // 原本是lisi,这里拼写错误,测试solr返回建议词语
        sq.set("q", "lisi");
        QueryResponse query = solrClient.query(sq);
        SolrDocumentList results = query.getResults();

        // 获取查询条数
        long count = results.getNumFound();

        // 判断是否查询到
        if (count == 0) {
            SpellCheckResponse spellCheckResponse = query
                    .getSpellCheckResponse();
            List<Collation> collatedResults = spellCheckResponse
                    .getCollatedResults();
            for (Collation collation : collatedResults) {
                long numberOfHits = collation.getNumberOfHits();
                System.out.println("建议条数为:" + numberOfHits);

                List<Correction> misspellingsAndCorrections = collation
                        .getMisspellingsAndCorrections();
                for (Correction correction : misspellingsAndCorrections) {
                    String source = correction.getOriginal();
                    String current = correction.getCorrection();
                    System.out.println("推荐词语为:" + current + "原始的输入为:" + source);
                }
            }
        } else {
            for (SolrDocument solrDocument : results) {
                // 获取key集合
                Collection<String> fieldNames = solrDocument.getFieldNames();

                // 根据key集合输出value
                for (String field : fieldNames) {
                    System.out.println("key: " + field + ",value: "
                            + solrDocument.get(field));
                }
            }
        }

        // 关闭连接
        commitAndCloseSolr(solrClient);
    }

    /**
     * 提交以及关闭服务
     *
     * @param solrClient
     * @throws Exception
     */
    private static void commitAndCloseSolr(HttpSolrClient solrClient)
            throws Exception {
        solrClient.commit();
        solrClient.close();
    }

}


在根据id进行查询的时候,报了个类型不匹配的错误:

1.获取document数据-------------------------
一共查询到1条记录
id:00004
name:lisi
age:[25]
addr:重庆
2.获取对象信息,需要传入对应对象的类class-----------
Exception in thread "main" org.apache.solr.client.solrj.beans.BindingException: Could not instantiate object 
of class com.sa.pojo.Person
	at org.apache.solr.client.solrj.beans.DocumentObjectBinder.getBean(DocumentObjectBinder.java:71)
	at org.apache.solr.client.solrj.beans.DocumentObjectBinder.getBeans(DocumentObjectBinder.java:50)
	at org.apache.solr.client.solrj.response.QueryResponse.getBeans(QueryResponse.java:618)
	at com.sa.solr.SolrTest.getDocument(SolrTest.java:238)
	at com.sa.solr.SolrTest.main(SolrTest.java:84)
Caused by: org.apache.solr.client.solrj.beans.BindingException: Exception while setting value :
 [25] on private java.lang.Integer com.sa.pojo.Person.age
	at org.apache.solr.client.solrj.beans.DocumentObjectBinder$DocField.set(DocumentObjectBinder.java:455)
	at org.apache.solr.client.solrj.beans.DocumentObjectBinder$DocField.inject(DocumentObjectBinder.java:438)
	at org.apache.solr.client.solrj.beans.DocumentObjectBinder.getBean(DocumentObjectBinder.java:67)
	... 4 more
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Integer field com.sa.pojo.Person.age to java.util.ArrayList
	at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
	at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
	at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
	at java.lang.reflect.Field.set(Field.java:764)
	at org.apache.solr.client.solrj.beans.DocumentObjectBinder$DocField.set(DocumentObjectBinder.java:449)
	... 6 more

到solr控制台查这个id为0004d person:

看到了没,它在存到solr的时候就多了中括号!

查看core1下的managed-schema文件,打开找到field位置,查看与person类相关的field:

  <field name="addr" type="string"/>
  <field name="age" type="plongs"/>
  <field name="id" type="string" multiValued="false" indexed="true" required="true" stored="true"/>
  <field name="name" type="string"/>

age原本在类中设置的是integer类型,到了这里变成了plongs!尝试将其改为匹配java integer类型的solr类型pint。

 <field name="addr" type="string"/>
  <field name="age" type="pint"/>
  <field name="id" type="string" multiValued="false" indexed="true" required="true" stored="true"/>
  <field name="name" type="string"/>

刷新core1:



再次到solr控制台查这个id为0004d person:


发现age变正常了!!

尝试运行java代码,看是否还报异常:

1.获取document数据-------------------------
一共查询到1条记录
id:00004
name:lisi
age:25
addr:重庆
2.获取对象信息,需要传入对应对象的类class-----------
一共查询到1条记录
Person{id='00004', name='lisi', age=25, addr='重庆'}

一切正常,呜哈哈~~~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值