springboot整合elasticsearch 实现增删改查

该博客介绍了如何使用Spring Boot集成Elasticsearch进行数据操作,包括查询、添加、删除和更新索引。示例代码展示了如何创建索引、批量创建索引、删除索引、更新索引以及按条件查询索引列表。此外,还使用了自定义的BeanUtils工具类进行对象间的属性拷贝。
摘要由CSDN通过智能技术生成

目前实现的功能有查询单个实体类,通过条件查询List,单个新增,批量新增,通过id删除,批量删除,

单个修改,

项目用到的类

pom.xml

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>

 配置文件

spring:
  data:
    elasticsearch:
      repositories:
        enabled: true
      cluster-name: my-es
      cluster-nodes: 42.194.130.93:9300
environment: 开发环境
ev:
  expressIndex: express_dev

 

ExpressIndexService类
   /**
     * 批量创建索引
     * @param expressList
     */
    void batchCreateIndex(List<ExpressDO> expressList);

    /**
     * 批量创建索引
     * @param express
     */
    void createIndex(ExpressDO express);

    /**
     * 批量删除索引
     */
    void deleteAllIndex();

    /**
     * 删除索引
     */
    void deleteIndex(Long id);

    /**
     * 修改索引
     * @param express
     */
    void updateIndex(ExpressDO express);

    /**
     * 查询索引
     * @param
     */
    ExpressDO seletctIndex(Long id);

    /**
     * 查询索引列表
     * @param
     */
    List<ExpressDO> seletctAllIndex(ExpressDO express, EsPager pager);
ExpressIndexServiceImpl类
package com.bootdo.es.service.impl;

import com.bootdo.es.domain.EsPager;
import com.bootdo.es.domain.ExpressIndex;
import com.bootdo.es.service.ExpressIndexRepository;
import com.bootdo.es.service.ExpressIndexService;
import com.bootdo.system.domain.ExpressDO;

import com.bootdo.system.util.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class ExpressIndexServiceImpl implements ExpressIndexService {

    @Autowired
    private ExpressIndexRepository expressIndexRepository;

    /**
     * 批量创建索引
     * @param expressList
     */
    @Override
    public void batchCreateIndex(List<ExpressDO> expressList) {
        List<ExpressIndex> expressAddIndexList = BeanUtils.cloneList(expressList, ExpressIndex.class);
        expressIndexRepository.saveAll(expressAddIndexList);
    }

    /**
     * 创建索引
     * @param express
     */
    @Override
    public void createIndex(ExpressDO express) {
        ExpressIndex expressIndex = BeanUtils.clone(express,ExpressIndex.class);
        expressIndexRepository.save(expressIndex);
    }

    /**
     * 批量删除索引
     * @param
     */
    @Override
    public void deleteAllIndex() {
        expressIndexRepository.deleteAll();
    }

    /**
     * 删除索引
     * @param
     */
    @Override
    public void deleteIndex(Long id) {
        expressIndexRepository.deleteById(id);
    }

    /**
     * 修改索引
     * @param
     */
    @Override
    public void updateIndex(ExpressDO express) {
        //删除索引
        expressIndexRepository.deleteById(Long.valueOf(express.getMealid()));
        //创建索引
        ExpressIndex expressIndex = BeanUtils.clone(express,ExpressIndex.class);
        expressIndexRepository.save(expressIndex);
    }

    /**
     * 查询索引列表
     * @param
     */
   @Override
    public List<ExpressDO> seletctAllIndex(ExpressDO express, EsPager pager) {
       // 构建查询条件
       NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
       BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

       if (StringUtils.isNotEmpty(express.getUsername())) {
           // 创建模糊查询语句 ES中must和should不能同时使用 同时使用should失效 嵌套多个must 将should条件拼接在一个must中即可
           BoolQueryBuilder shouldQuery = QueryBuilders.boolQuery()
                   .should(QueryBuilders.wildcardQuery("username", "*"+express.getUsername()+"*"))
                   .should(QueryBuilders.wildcardQuery("phone", "*"+express.getUsername()+"*"));
           boolQueryBuilder.must(shouldQuery);
       }
       queryBuilder.withSort(SortBuilders.fieldSort("createdate").order(SortOrder.ASC)); //排序
       if(null != express.getAddress()){
           boolQueryBuilder.must(QueryBuilders.termQuery("address", express.getAddress())); //条件查询
       }
       queryBuilder.withQuery(boolQueryBuilder);

       //页码设置
       int pagetSize = pager.getPageSize();
       queryBuilder.withPageable(PageRequest.of(pager.getPageNo() - 1,pagetSize));
       Page<ExpressIndex> pageList = expressIndexRepository.search(queryBuilder.build());
       List<ExpressDO> list = BeanUtils.cloneList(pageList.getContent(), ExpressDO.class) ;
       return list;

    }

    /**
     * 查询索引
     * @param
     */
    @Override
    public ExpressDO seletctIndex(Long id) {
        Optional<ExpressIndex> expressIndex =  expressIndexRepository.findById(id);
        if(expressIndex != null){
            ExpressDO expressDO = BeanUtils.clone(expressIndex.get(),ExpressDO.class);
            return expressDO;
        }
        return new ExpressDO();

    }
}
ExpressIndexRepository类
package com.bootdo.es.service;

import com.bootdo.es.domain.ExpressIndex;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;


public interface ExpressIndexRepository extends ElasticsearchRepository<ExpressIndex,Long> {
}

EV类

package com.bootdo.es.domain;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class EV {

    @Value("${ev.expressIndex}")
    private String expressIndex;

/*    @Value("${ev.courseChapterIndex}")
    private String courseChapterIndex;
    @Value("${ev.courseItemIndex}")
    private String courseItemIndex;*/

    @Bean
    public String expressIndex(){
        return expressIndex;
    }

/*    @Bean
    public String courseChapterIndex(){
        return courseChapterIndex;
    }
    @Bean
    public String courseItemIndex(){
        return courseItemIndex;
    }*/

}
EsPager类
package com.bootdo.es.domain;


import java.io.Serializable;

/**
 * 分页对象
 * @author dengzw
 * 2018-6-4 下午9:26:15
 *
 */
public class EsPager extends Pager implements Serializable{


	
}
ExpressIndex类
package com.bootdo.es.domain;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

@Document(indexName = "#{@expressIndex}", type = "docs", shards = 1, replicas = 1)
public class ExpressIndex implements Serializable {

    @Id
    private Integer mealid;

    //下单人姓名
    @Field(type = FieldType.Text, analyzer = "username")
    private String username;

    //下单人手机号
    @Field(type = FieldType.Text, analyzer = "phone")
    private String phone;

    //订单号
    @Field(type = FieldType.Text, analyzer = "orderno")
    private String orderno;

    //取件码
    @Field(type = FieldType.Text, analyzer = "pickcodce")
    private String pickcodce;

    //价格
    @Field(type = FieldType.Double, analyzer = "price")
    private BigDecimal price;

    //订单物品
    @Field(type = FieldType.Text, analyzer = "goods")
    private String goods;

    //收件人姓名
    @Field(type = FieldType.Text, analyzer = "collectname")
    private String collectname;

    //收件人手机号
    @Field(type = FieldType.Text, analyzer = "collectphone")
    private String collectphone;

    //始发地
    @Field(type = FieldType.Text, analyzer = "start")
    private String start;

    //目的地
    @Field(type = FieldType.Text, analyzer = "address")
    private String address;

    //订单状态 1待接单,2已接单,3已完成
    @Field(type = FieldType.Integer, analyzer = "status")
    private Integer status;

    //类型 1快递,2外卖,3跑腿
    @Field(type = FieldType.Integer, analyzer = "type")
    private Integer type;

    //快递类型 1代寄,2代取
    @Field(type = FieldType.Integer, analyzer = "expresstype")
    private Integer expresstype;

    //接单时间
    @Field(type = FieldType.Date, analyzer = "receivingdate")
    private Date receivingdate;

    //接单人
    @Field(type = FieldType.Long, analyzer = "receivinguserid")
    private Long receivinguserid;

    //修改时间
    @Field(type = FieldType.Date, analyzer = "updatedate")
    private Date updatedate;

    //创建时间
    @Field(type = FieldType.Date, analyzer = "createdate")
    private Date createdate;

    @Field(type = FieldType.Text, analyzer = "receivingName")
    private String receivingName;

    @Field(type = FieldType.Text, analyzer = "mobile")
    private String mobile;

    public Integer getMealid() {
        return mealid;
    }

    public void setMealid(Integer mealid) {
        this.mealid = mealid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getOrderno() {
        return orderno;
    }

    public void setOrderno(String orderno) {
        this.orderno = orderno;
    }

    public String getPickcodce() {
        return pickcodce;
    }

    public void setPickcodce(String pickcodce) {
        this.pickcodce = pickcodce;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getGoods() {
        return goods;
    }

    public void setGoods(String goods) {
        this.goods = goods;
    }

    public String getCollectname() {
        return collectname;
    }

    public void setCollectname(String collectname) {
        this.collectname = collectname;
    }

    public String getCollectphone() {
        return collectphone;
    }

    public void setCollectphone(String collectphone) {
        this.collectphone = collectphone;
    }

    public String getStart() {
        return start;
    }

    public void setStart(String start) {
        this.start = start;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public Integer getExpresstype() {
        return expresstype;
    }

    public void setExpresstype(Integer expresstype) {
        this.expresstype = expresstype;
    }

    public Date getReceivingdate() {
        return receivingdate;
    }

    public void setReceivingdate(Date receivingdate) {
        this.receivingdate = receivingdate;
    }

    public Long getReceivinguserid() {
        return receivinguserid;
    }

    public void setReceivinguserid(Long receivinguserid) {
        this.receivinguserid = receivinguserid;
    }

    public Date getUpdatedate() {
        return updatedate;
    }

    public void setUpdatedate(Date updatedate) {
        this.updatedate = updatedate;
    }

    public Date getCreatedate() {
        return createdate;
    }

    public void setCreatedate(Date createdate) {
        this.createdate = createdate;
    }

    public String getReceivingName() {
        return receivingName;
    }

    public void setReceivingName(String receivingName) {
        this.receivingName = receivingName;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}
Pager类
package com.bootdo.es.domain;
import java.io.Serializable;
import java.util.List;

/**
 * @Description: 分页对象
 * @Author : zhuzq
 * @Date: 2020/8/7 15:21
 * @return:
 **/
public class Pager<C> implements Serializable{

	private static final long serialVersionUID = 1L;
	private int pageSize = 10;		// 每页多少条
	private int pageNo = 1; 		// 第几页
	private int totalPages = 10;	// 总的页数
	private int totalSize = 0;	// 总的记录数
	private List<?> list ;

	public Pager() {
	}

	public Pager(int pageNo, int pageSize) {
		super();
		this.pageSize = pageSize;
		this.pageNo = pageNo;
	}

	public int getBegin() {
		return (this.getPageNo() - 1) * this.getPageSize();
	}

	public int getEnd() {
		return (this.getPageNo() - 1) * this.getPageSize() + this.getPageSize();
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		if (pageSize < 1) {
			this.pageSize = 10;
		} else {
			this.pageSize = pageSize;
		}
	}

	public int getPageNo() {
		if (this.pageNo > this.getTotalPages() && this.getTotalSize() > 0) {
			this.pageNo = this.getTotalPages(); // 如果当前页大于最大页数,则等于最大页数
			//this.pageNo = -1; //修改这里用户手机客户端.
		}
		return pageNo;
	}


	public void setPageNo(int pageNo) {
		if (pageNo < 1) {
			this.pageNo = 1;
		} else {
			this.pageNo = pageNo;
		}
	}

	public int getTotalPages() {
		totalPages = totalPages < 1 ? 1 : totalPages;
		totalPages = getTotalSize() % getPageSize() == 0 ? (getTotalSize() / getPageSize()) : (getTotalSize() / getPageSize() + 1);
		return totalPages;
	}

	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}

	public int getTotalSize() {
		return totalSize;
	}

	public void setTotalSize(int totalSize) {
		this.totalSize = totalSize;
	}

	public List<?> getList() {
		return list;
	}

	public void setList(List<?> list) {
		this.list = list;
	}

	@Override
	public String toString() {
		return "Pager{" +
				"pageSize=" + pageSize +
				", pageNo=" + pageNo +
				", totalPages=" + totalPages +
				", totalSize=" + totalSize +
				", list=" + list +
				'}';
	}
}
BeanUtils复制拷贝类
package com.bootdo.system.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;


/**
 * 摘要:Bean拷贝工具类
 * @author Williams.li
 * @version 1.0
 * @Date 2016年12月21日
 */
public class BeanUtils extends org.apache.commons.beanutils.BeanUtils{
	private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);
	
	@SuppressWarnings("rawtypes")
	private static Map<Class, List<Field>> fieldsMap = new HashMap<Class, List<Field>>();
	
	/**
	 * 拷贝list列表(排除Null)
	 * @param sourceList    源列表
	 * @param targetClass   目标class
	 */
	public static <T> List<T> copyList(List<?> sourceList, Class<T> targetClass) {
		if(null == sourceList || sourceList.size() == 0){
			return null;
		}
		try{
			List<T> targetList = new ArrayList<T>(sourceList.size());
			for(Object source : sourceList){
				T target = targetClass.newInstance();
				BeanUtils.copyNotNull(target,source);
				targetList.add(target);
			}
			return targetList;
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return null;
		}
	}

	/**
	 * 拷贝Object(排除Null)
	 * @param target 目标
	 * @param orig 源
	 */
	public static <T> T copyNotNull(Class<T> targetClass, Object orig) {
		if( null == orig){
			return null;
		}
		try {
			T target = targetClass.newInstance();
			return copy(target, orig, false);
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return null;
		}
	}
	
	/**
	 * 拷贝Object(排除Null)
	 * @param target 目标
	 * @param orig 源
	 */
	public static <T> T copyNotNull(T target, Object orig) {
		if(null == target || null == orig){
			return null;
		}
		return copy(target, orig, false);
	}
	
	

	@SuppressWarnings("unchecked")
	public static <T> T copy(T target, Object orig, boolean includedNull, String... ignoreProperties) {
		if(null == target || null == orig){
			return null;
		}
		try {
			if (includedNull && ignoreProperties == null) {
				PropertyUtils.copyProperties(target, orig);
			} else {
				List<String> ignoreFields = new ArrayList<String>();
				if (ignoreProperties != null) {
					for (String p : ignoreProperties) {
						ignoreFields.add(p);
					}
				}
				if (!includedNull) {
					Map<String, Object> parameterMap = new BeanMap(orig);
					for (Entry<String, Object> entry : parameterMap.entrySet()) {
						if (entry.getValue() == null || "".equals(entry.getValue())) {
							String fieldName = entry.getKey();
							if (!ignoreFields.contains(fieldName)) {
								ignoreFields.add(fieldName);
							}
						}
					}
				}
				org.springframework.beans.BeanUtils.copyProperties(orig, target,
						ignoreFields.toArray(new String[ignoreFields.size()]));
			}
			return target;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	public static List<Field> getAllFields(Class<?> clazz) {
		if (!ClassUtils.isCglibProxyClass(clazz)) {
			List<Field> result = fieldsMap.get(clazz);
			if (result == null) {
				result = _getAllFields(clazz);
				fieldsMap.put(clazz, result);
			}
			return result;
		} else {
			return _getAllFields(clazz);
		}
	}

	private static List<Field> _getAllFields(Class<?> clazz) {
		List<Field> fieldList = new ArrayList<Field>();
		for (Field field : clazz.getDeclaredFields()) {
			fieldList.add(field);
		}
		Class<?> c = clazz.getSuperclass();
		if (c != null) {
			fieldList.addAll(getAllFields(c));
		}
		return fieldList;
	}

	/**
	 * Get field in class and its super class
	 * 
	 * @param clazz
	 * @param fieldName
	 * @return
	 */
	public static Field getField(Class<?> clazz, String fieldName) {
		for (Field field : clazz.getDeclaredFields()) {
			if (field.getName().equals(fieldName)) {
				return field;
			}
		}
		Class<?> c = clazz.getSuperclass();
		if (c != null) {
			return getField(c, fieldName);
		}
		return null;
	}

	/**
	 * 字符数组合并 注:接受多个数组参数的输入,合并成一个数组并返回。
	 * 
	 * @param arr
	 *            输入的数组参数,一个或若干个
	 * @return
	 */
	public static String[] getMergeArray(String[]... arr) {
		if (arr == null)
			return null;
		int length = 0;
		for (Object[] obj : arr) {
			length += obj.length;
		}
		String[] result = new String[length];
		length = 0;
		for (int i = 0; i < arr.length; i++) {
			System.arraycopy(arr[i], 0, result, length, arr[i].length);
			length += arr[i].length;
		}
		return result;
	}

	public static <T> T clone(Object obj, Class<T> targetClazz) {
		try {
			return copy(targetClazz.newInstance(), obj, false);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}


	
	public static <M> List<M> cloneList(List<?> srcList, Class<M> targetClazz) {
		return ListUtil.clone(srcList, targetClazz);
	}

	@SuppressWarnings("unchecked")
	public static <T> List<T> createList(T... objs) {
		return ListUtil.createList(objs);
	}

	/**
	 * 功能:将bean对象转换为url参数
	 */
	public static String  bean2urlparam(Object obj){
		try{
			StringBuilder builder = new StringBuilder();
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());  
	        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
	        for (PropertyDescriptor property : propertyDescriptors) {  
	             String propKey = property.getName();
	             if(!"class".equals(propKey)){
	            	 Object propVal = PropertyUtils.getProperty(obj, propKey);
	            	 if(propVal  != null && StringUtil.isNotEmpty(propVal.toString())){
	            		 builder.append(propKey).append("=").append(propVal).append("&");
	            	 }
	             }
	        }
	        if(builder.length() > 0){
	        	return builder.deleteCharAt(builder.length()-1).toString();
	        }
		}catch(Exception e){
			logger.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 功能:将url中的对应obj中的属性参数值替换
	 */
	public static String  bean2urlparam(Object obj,String param){
		try{
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());  
	        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
	        String newStr = param;
	        for (PropertyDescriptor property : propertyDescriptors) {  
	             String propKey = property.getName();
	             if(!"class".equals(propKey)){
	            	 Object propVal = PropertyUtils.getProperty(obj, propKey);
	            	 if(propVal  != null && StringUtil.isNotEmpty(propVal.toString())){
	            		 newStr = newStr.replaceAll("="+propKey,"="+propVal.toString());
	            		 continue;
	            	 }
	             }
	        }
	        return newStr;
		}catch(Exception e){
			logger.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 功能:将url中的对应obj和map中的属性参数值替换
	 */
	public static String  bean2urlparam(Object obj,String param,Map<String,Object> plus){
		try{
			String newParam = bean2urlparam(obj,param);
			if(!CollectionUtils.isEmpty(plus)){
				for(Entry<String,Object> entry : plus.entrySet()){
					Object propVal = entry.getValue();
					if(propVal  != null && StringUtil.isNotEmpty(propVal.toString())){
						newParam = newParam.replaceAll("="+entry.getKey(),"="+propVal.toString());
					}
				}
			}
			if(newParam.indexOf("#")  != -1){
				newParam = newParam.replaceAll("#","");
			}
			return newParam;
		}catch(Exception e){
			logger.error(e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 功能:将URL参数转换为map
	 */
	public static Map<String,String>  urlparam2map(String param){
		if(StringUtils.isNotEmpty(param)){
			Map<String,String> map = null;
			String[] arr = StringUtils.split(param, "&");
			if(arr != null && arr.length > 0){
				map = new HashMap<String,String>();
				for(String item : arr){
					String[] eqArr = item.split("=");
					map.put(eqArr[0], eqArr[1]);
				}
				return map;
			}
		}
		return null;
	}
	
	/**
	 * 功能:将URL参数转换为JSONObject
	 */
	public static JSONObject urlparam2json(String param){
		JSONObject paramJSON = new JSONObject();
		if(StringUtils.isNotEmpty(param)){
			String[] arr = StringUtils.split(param, "&");
			if(arr != null && arr.length > 0){
				for(String item : arr){
					String[] eqArr = item.split("=");
					paramJSON.put(eqArr[0], eqArr[1]);
				}
			}
		}
		return paramJSON;
	}
	
	/**
	 * 将一个 Map 对象转化为一个 JavaBean
	 * 
	 * @param clazz
	 *            要转化的类型
	 * @param map
	 *            包含属性值的 map
	 * @return 转化出来的 JavaBean 对象
	 * @throws IntrospectionException
	 *             如果分析类属性失败
	 * @throws IllegalAccessException
	 *             如果实例化 JavaBean 失败
	 * @throws InstantiationException
	 *             如果实例化 JavaBean 失败
	 * @throws InvocationTargetException
	 *             如果调用属性的 setter 方法失败
	 */
	@SuppressWarnings("rawtypes")
	public static <T> T toBean(Class<T> clazz, Map map) {
		T obj = null;
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
			obj = clazz.newInstance(); // 创建 JavaBean 对象

			// 给 JavaBean 对象的属性赋值
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (int i = 0; i < propertyDescriptors.length; i++) {
				PropertyDescriptor descriptor = propertyDescriptors[i];
				String propertyName = descriptor.getName();
				if (map.containsKey(propertyName)) {
					// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
					Object value = map.get(propertyName);
					if ("".equals(value)) {
						value = null;
					}
					Object[] args = new Object[1];
					args[0] = value;
					try {
						descriptor.getWriteMethod().invoke(obj, args);
					} catch (InvocationTargetException e) {
						logger.info("字段映射失败");
					}
				}
			}
		} catch (IllegalAccessException e) {
			logger.info("实例化 JavaBean 失败");
		} catch (IntrospectionException e) {
			logger.info("分析类属性失败");
		} catch (IllegalArgumentException e) {
			logger.info("映射错误");
		} catch (InstantiationException e) {
			logger.info("实例化 JavaBean 失败");
		}
		return (T) obj;
	}

	/**
	 * 将一个 JavaBean 对象转化为一个 Map
	 * 
	 * @param bean
	 *            要转化的JavaBean 对象
	 * @return 转化出来的 Map 对象
	 * @throws IntrospectionException
	 *             如果分析类属性失败
	 * @throws IllegalAccessException
	 *             如果实例化 JavaBean 失败
	 * @throws InvocationTargetException
	 *             如果调用属性的 setter 方法失败
	 */
	public static Map<String,Object> toMap(Object bean) {
		Class<? extends Object> clazz = bean.getClass();
		Map<String, Object> returnMap = new HashMap<String, Object>();
		BeanInfo beanInfo = null;
		try {
			beanInfo = Introspector.getBeanInfo(clazz);
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (int i = 0; i < propertyDescriptors.length; i++) {
				PropertyDescriptor descriptor = propertyDescriptors[i];
				String propertyName = descriptor.getName();
				if (!propertyName.equals("class")) {
					Method readMethod = descriptor.getReadMethod();
					Object result = null;
					result = readMethod.invoke(bean, new Object[0]);
					if (null != propertyName) {
						propertyName = propertyName.toString();
					}
					if (null != result) {
						if(result instanceof Date){
							result = DateUtil.getDateFormat((Date)result);
						}else{
							result = result.toString();
						}
					}
					returnMap.put(propertyName, result);
				}
			}
		} catch (IntrospectionException e) {
			logger.info("分析类属性失败");
		} catch (IllegalAccessException e) {
			logger.info("实例化 JavaBean 失败");
		} catch (IllegalArgumentException e) {
			logger.info("映射错误");
		} catch (InvocationTargetException e) {
			logger.info("调用属性的 setter 方法失败");
		}
		return returnMap;
	}
	
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zengsange

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值