通過註解,實現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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章