通过注解,实现solr查询索引,直接返回java对象

1.注解类:@Documented
@Target(ElementType.FIELD) //作用范围: 字段
@Retention(RetentionPolicy.RUNTIME) // 作用时间: 运行时
public @interface SolrMapping {
String value() default “”; //solr索引名
}
2.转换类:
package com.xjs.common.solr;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.*;
import org.apache.solr.common.SolrDocument;
import java.lang.reflect.Field;
import java.math.BigDecimal;

public class Doc2BeanUtil {
public static Object getBean(Class beanClass, SolrDocument document) {
try {
//获取实例对象
Object bean = beanClass.newInstance();

        // 反射获得所有字段
        Field[] fields = beanClass.getDeclaredFields();
        // 遍历bean中的字段
        for (Field field : fields) {
            SolrMapping anno = field.getAnnotation(SolrMapping.class);
            if (anno != null) {
                String filedName = field.getName();
                //获得注解中标记的对应的索引域
                String indexName = anno.value();
                Object val = document.get(indexName);
                if("".equals(val)){
                    //如果注解不指定solr的索引,默认用字段名来作为索引名
                    val = filedName;
                }
                // 判断字段的类型
                //由于类型不为string时,有部分数据的值可能为null,需要重新定义
                ConvertUtils.register(new DateConverter(null), java.util.Date.class);
                ConvertUtils.register(new LongConverter(null), Long.class);
                ConvertUtils.register(new ShortConverter(null), Short.class);
                ConvertUtils.register(new IntegerConverter(null), Integer.class);
                ConvertUtils.register(new DoubleConverter(null), Double.class);
                ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
                BeanUtils.setProperty(bean,filedName,val);
            }
        }
        return bean;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

}

ConvertUtils.register(new Converter(){ public Date convert(Class type, Object value) { if(value != null){ try {

                    return new SimpleDateFormat("yyyy-MM-dd").parse(value.toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }//内部类:value接收data转换成string类型

            //SimpleDateFormat中的parse方法可以  把String型的字符串转换成特定格式的date类

            return null;
        }           
    }, Date.class);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章