当前位置:   article > 正文

springboot整合elasticsearch 实现增删改查_elasticsearch ,springboot中操作文档的增删改查

elasticsearch ,springboot中操作文档的增删改查

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

单个修改,

项目用到的类

pom.xml

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  4. </dependency>

 配置文件

  1. spring:
  2. data:
  3. elasticsearch:
  4. repositories:
  5. enabled: true
  6. cluster-name: my-es
  7. cluster-nodes: 42.194.130.93:9300
  8. environment: 开发环境
  9. ev:
  10. expressIndex: express_dev

 

ExpressIndexService类
  1. /**
  2. * 批量创建索引
  3. * @param expressList
  4. */
  5. void batchCreateIndex(List<ExpressDO> expressList);
  6. /**
  7. * 批量创建索引
  8. * @param express
  9. */
  10. void createIndex(ExpressDO express);
  11. /**
  12. * 批量删除索引
  13. */
  14. void deleteAllIndex();
  15. /**
  16. * 删除索引
  17. */
  18. void deleteIndex(Long id);
  19. /**
  20. * 修改索引
  21. * @param express
  22. */
  23. void updateIndex(ExpressDO express);
  24. /**
  25. * 查询索引
  26. * @param
  27. */
  28. ExpressDO seletctIndex(Long id);
  29. /**
  30. * 查询索引列表
  31. * @param
  32. */
  33. List<ExpressDO> seletctAllIndex(ExpressDO express, EsPager pager);
ExpressIndexServiceImpl类
  1. package com.bootdo.es.service.impl;
  2. import com.bootdo.es.domain.EsPager;
  3. import com.bootdo.es.domain.ExpressIndex;
  4. import com.bootdo.es.service.ExpressIndexRepository;
  5. import com.bootdo.es.service.ExpressIndexService;
  6. import com.bootdo.system.domain.ExpressDO;
  7. import com.bootdo.system.util.BeanUtils;
  8. import org.apache.commons.lang.StringUtils;
  9. import org.elasticsearch.index.query.BoolQueryBuilder;
  10. import org.elasticsearch.index.query.QueryBuilders;
  11. import org.elasticsearch.search.sort.SortBuilders;
  12. import org.elasticsearch.search.sort.SortOrder;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.data.domain.Page;
  15. import org.springframework.data.domain.PageRequest;
  16. import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
  17. import org.springframework.stereotype.Service;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. import java.util.Optional;
  21. @Service
  22. public class ExpressIndexServiceImpl implements ExpressIndexService {
  23. @Autowired
  24. private ExpressIndexRepository expressIndexRepository;
  25. /**
  26. * 批量创建索引
  27. * @param expressList
  28. */
  29. @Override
  30. public void batchCreateIndex(List<ExpressDO> expressList) {
  31. List<ExpressIndex> expressAddIndexList = BeanUtils.cloneList(expressList, ExpressIndex.class);
  32. expressIndexRepository.saveAll(expressAddIndexList);
  33. }
  34. /**
  35. * 创建索引
  36. * @param express
  37. */
  38. @Override
  39. public void createIndex(ExpressDO express) {
  40. ExpressIndex expressIndex = BeanUtils.clone(express,ExpressIndex.class);
  41. expressIndexRepository.save(expressIndex);
  42. }
  43. /**
  44. * 批量删除索引
  45. * @param
  46. */
  47. @Override
  48. public void deleteAllIndex() {
  49. expressIndexRepository.deleteAll();
  50. }
  51. /**
  52. * 删除索引
  53. * @param
  54. */
  55. @Override
  56. public void deleteIndex(Long id) {
  57. expressIndexRepository.deleteById(id);
  58. }
  59. /**
  60. * 修改索引
  61. * @param
  62. */
  63. @Override
  64. public void updateIndex(ExpressDO express) {
  65. //删除索引
  66. expressIndexRepository.deleteById(Long.valueOf(express.getMealid()));
  67. //创建索引
  68. ExpressIndex expressIndex = BeanUtils.clone(express,ExpressIndex.class);
  69. expressIndexRepository.save(expressIndex);
  70. }
  71. /**
  72. * 查询索引列表
  73. * @param
  74. */
  75. @Override
  76. public List<ExpressDO> seletctAllIndex(ExpressDO express, EsPager pager) {
  77. // 构建查询条件
  78. NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
  79. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  80. if (StringUtils.isNotEmpty(express.getUsername())) {
  81. // 创建模糊查询语句 ES中must和should不能同时使用 同时使用should失效 嵌套多个must 将should条件拼接在一个must中即可
  82. BoolQueryBuilder shouldQuery = QueryBuilders.boolQuery()
  83. .should(QueryBuilders.wildcardQuery("username", "*"+express.getUsername()+"*"))
  84. .should(QueryBuilders.wildcardQuery("phone", "*"+express.getUsername()+"*"));
  85. boolQueryBuilder.must(shouldQuery);
  86. }
  87. queryBuilder.withSort(SortBuilders.fieldSort("createdate").order(SortOrder.ASC)); //排序
  88. if(null != express.getAddress()){
  89. boolQueryBuilder.must(QueryBuilders.termQuery("address", express.getAddress())); //条件查询
  90. }
  91. queryBuilder.withQuery(boolQueryBuilder);
  92. //页码设置
  93. int pagetSize = pager.getPageSize();
  94. queryBuilder.withPageable(PageRequest.of(pager.getPageNo() - 1,pagetSize));
  95. Page<ExpressIndex> pageList = expressIndexRepository.search(queryBuilder.build());
  96. List<ExpressDO> list = BeanUtils.cloneList(pageList.getContent(), ExpressDO.class) ;
  97. return list;
  98. }
  99. /**
  100. * 查询索引
  101. * @param
  102. */
  103. @Override
  104. public ExpressDO seletctIndex(Long id) {
  105. Optional<ExpressIndex> expressIndex = expressIndexRepository.findById(id);
  106. if(expressIndex != null){
  107. ExpressDO expressDO = BeanUtils.clone(expressIndex.get(),ExpressDO.class);
  108. return expressDO;
  109. }
  110. return new ExpressDO();
  111. }
  112. }
ExpressIndexRepository类
  1. package com.bootdo.es.service;
  2. import com.bootdo.es.domain.ExpressIndex;
  3. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  4. public interface ExpressIndexRepository extends ElasticsearchRepository<ExpressIndex,Long> {
  5. }

EV类

  1. package com.bootdo.es.domain;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. public class EV {
  7. @Value("${ev.expressIndex}")
  8. private String expressIndex;
  9. /* @Value("${ev.courseChapterIndex}")
  10. private String courseChapterIndex;
  11. @Value("${ev.courseItemIndex}")
  12. private String courseItemIndex;*/
  13. @Bean
  14. public String expressIndex(){
  15. return expressIndex;
  16. }
  17. /* @Bean
  18. public String courseChapterIndex(){
  19. return courseChapterIndex;
  20. }
  21. @Bean
  22. public String courseItemIndex(){
  23. return courseItemIndex;
  24. }*/
  25. }
EsPager类
  1. package com.bootdo.es.domain;
  2. import java.io.Serializable;
  3. /**
  4. * 分页对象
  5. * @author dengzw
  6. * 2018-6-4 下午9:26:15
  7. *
  8. */
  9. public class EsPager extends Pager implements Serializable{
  10. }
ExpressIndex类
  1. package com.bootdo.es.domain;
  2. import org.springframework.data.annotation.Id;
  3. import org.springframework.data.elasticsearch.annotations.Document;
  4. import org.springframework.data.elasticsearch.annotations.Field;
  5. import org.springframework.data.elasticsearch.annotations.FieldType;
  6. import java.io.Serializable;
  7. import java.math.BigDecimal;
  8. import java.util.Date;
  9. @Document(indexName = "#{@expressIndex}", type = "docs", shards = 1, replicas = 1)
  10. public class ExpressIndex implements Serializable {
  11. @Id
  12. private Integer mealid;
  13. //下单人姓名
  14. @Field(type = FieldType.Text, analyzer = "username")
  15. private String username;
  16. //下单人手机号
  17. @Field(type = FieldType.Text, analyzer = "phone")
  18. private String phone;
  19. //订单号
  20. @Field(type = FieldType.Text, analyzer = "orderno")
  21. private String orderno;
  22. //取件码
  23. @Field(type = FieldType.Text, analyzer = "pickcodce")
  24. private String pickcodce;
  25. //价格
  26. @Field(type = FieldType.Double, analyzer = "price")
  27. private BigDecimal price;
  28. //订单物品
  29. @Field(type = FieldType.Text, analyzer = "goods")
  30. private String goods;
  31. //收件人姓名
  32. @Field(type = FieldType.Text, analyzer = "collectname")
  33. private String collectname;
  34. //收件人手机号
  35. @Field(type = FieldType.Text, analyzer = "collectphone")
  36. private String collectphone;
  37. //始发地
  38. @Field(type = FieldType.Text, analyzer = "start")
  39. private String start;
  40. //目的地
  41. @Field(type = FieldType.Text, analyzer = "address")
  42. private String address;
  43. //订单状态 1待接单,2已接单,3已完成
  44. @Field(type = FieldType.Integer, analyzer = "status")
  45. private Integer status;
  46. //类型 1快递,2外卖,3跑腿
  47. @Field(type = FieldType.Integer, analyzer = "type")
  48. private Integer type;
  49. //快递类型 1代寄,2代取
  50. @Field(type = FieldType.Integer, analyzer = "expresstype")
  51. private Integer expresstype;
  52. //接单时间
  53. @Field(type = FieldType.Date, analyzer = "receivingdate")
  54. private Date receivingdate;
  55. //接单人
  56. @Field(type = FieldType.Long, analyzer = "receivinguserid")
  57. private Long receivinguserid;
  58. //修改时间
  59. @Field(type = FieldType.Date, analyzer = "updatedate")
  60. private Date updatedate;
  61. //创建时间
  62. @Field(type = FieldType.Date, analyzer = "createdate")
  63. private Date createdate;
  64. @Field(type = FieldType.Text, analyzer = "receivingName")
  65. private String receivingName;
  66. @Field(type = FieldType.Text, analyzer = "mobile")
  67. private String mobile;
  68. public Integer getMealid() {
  69. return mealid;
  70. }
  71. public void setMealid(Integer mealid) {
  72. this.mealid = mealid;
  73. }
  74. public String getUsername() {
  75. return username;
  76. }
  77. public void setUsername(String username) {
  78. this.username = username;
  79. }
  80. public String getPhone() {
  81. return phone;
  82. }
  83. public void setPhone(String phone) {
  84. this.phone = phone;
  85. }
  86. public String getOrderno() {
  87. return orderno;
  88. }
  89. public void setOrderno(String orderno) {
  90. this.orderno = orderno;
  91. }
  92. public String getPickcodce() {
  93. return pickcodce;
  94. }
  95. public void setPickcodce(String pickcodce) {
  96. this.pickcodce = pickcodce;
  97. }
  98. public BigDecimal getPrice() {
  99. return price;
  100. }
  101. public void setPrice(BigDecimal price) {
  102. this.price = price;
  103. }
  104. public String getGoods() {
  105. return goods;
  106. }
  107. public void setGoods(String goods) {
  108. this.goods = goods;
  109. }
  110. public String getCollectname() {
  111. return collectname;
  112. }
  113. public void setCollectname(String collectname) {
  114. this.collectname = collectname;
  115. }
  116. public String getCollectphone() {
  117. return collectphone;
  118. }
  119. public void setCollectphone(String collectphone) {
  120. this.collectphone = collectphone;
  121. }
  122. public String getStart() {
  123. return start;
  124. }
  125. public void setStart(String start) {
  126. this.start = start;
  127. }
  128. public String getAddress() {
  129. return address;
  130. }
  131. public void setAddress(String address) {
  132. this.address = address;
  133. }
  134. public Integer getStatus() {
  135. return status;
  136. }
  137. public void setStatus(Integer status) {
  138. this.status = status;
  139. }
  140. public Integer getType() {
  141. return type;
  142. }
  143. public void setType(Integer type) {
  144. this.type = type;
  145. }
  146. public Integer getExpresstype() {
  147. return expresstype;
  148. }
  149. public void setExpresstype(Integer expresstype) {
  150. this.expresstype = expresstype;
  151. }
  152. public Date getReceivingdate() {
  153. return receivingdate;
  154. }
  155. public void setReceivingdate(Date receivingdate) {
  156. this.receivingdate = receivingdate;
  157. }
  158. public Long getReceivinguserid() {
  159. return receivinguserid;
  160. }
  161. public void setReceivinguserid(Long receivinguserid) {
  162. this.receivinguserid = receivinguserid;
  163. }
  164. public Date getUpdatedate() {
  165. return updatedate;
  166. }
  167. public void setUpdatedate(Date updatedate) {
  168. this.updatedate = updatedate;
  169. }
  170. public Date getCreatedate() {
  171. return createdate;
  172. }
  173. public void setCreatedate(Date createdate) {
  174. this.createdate = createdate;
  175. }
  176. public String getReceivingName() {
  177. return receivingName;
  178. }
  179. public void setReceivingName(String receivingName) {
  180. this.receivingName = receivingName;
  181. }
  182. public String getMobile() {
  183. return mobile;
  184. }
  185. public void setMobile(String mobile) {
  186. this.mobile = mobile;
  187. }
  188. }
Pager类
  1. package com.bootdo.es.domain;
  2. import java.io.Serializable;
  3. import java.util.List;
  4. /**
  5. * @Description: 分页对象
  6. * @Author : zhuzq
  7. * @Date: 2020/8/7 15:21
  8. * @return:
  9. **/
  10. public class Pager<C> implements Serializable{
  11. private static final long serialVersionUID = 1L;
  12. private int pageSize = 10; // 每页多少条
  13. private int pageNo = 1; // 第几页
  14. private int totalPages = 10; // 总的页数
  15. private int totalSize = 0; // 总的记录数
  16. private List<?> list ;
  17. public Pager() {
  18. }
  19. public Pager(int pageNo, int pageSize) {
  20. super();
  21. this.pageSize = pageSize;
  22. this.pageNo = pageNo;
  23. }
  24. public int getBegin() {
  25. return (this.getPageNo() - 1) * this.getPageSize();
  26. }
  27. public int getEnd() {
  28. return (this.getPageNo() - 1) * this.getPageSize() + this.getPageSize();
  29. }
  30. public int getPageSize() {
  31. return pageSize;
  32. }
  33. public void setPageSize(int pageSize) {
  34. if (pageSize < 1) {
  35. this.pageSize = 10;
  36. } else {
  37. this.pageSize = pageSize;
  38. }
  39. }
  40. public int getPageNo() {
  41. if (this.pageNo > this.getTotalPages() && this.getTotalSize() > 0) {
  42. this.pageNo = this.getTotalPages(); // 如果当前页大于最大页数,则等于最大页数
  43. //this.pageNo = -1; //修改这里用户手机客户端.
  44. }
  45. return pageNo;
  46. }
  47. public void setPageNo(int pageNo) {
  48. if (pageNo < 1) {
  49. this.pageNo = 1;
  50. } else {
  51. this.pageNo = pageNo;
  52. }
  53. }
  54. public int getTotalPages() {
  55. totalPages = totalPages < 1 ? 1 : totalPages;
  56. totalPages = getTotalSize() % getPageSize() == 0 ? (getTotalSize() / getPageSize()) : (getTotalSize() / getPageSize() + 1);
  57. return totalPages;
  58. }
  59. public void setTotalPages(int totalPages) {
  60. this.totalPages = totalPages;
  61. }
  62. public int getTotalSize() {
  63. return totalSize;
  64. }
  65. public void setTotalSize(int totalSize) {
  66. this.totalSize = totalSize;
  67. }
  68. public List<?> getList() {
  69. return list;
  70. }
  71. public void setList(List<?> list) {
  72. this.list = list;
  73. }
  74. @Override
  75. public String toString() {
  76. return "Pager{" +
  77. "pageSize=" + pageSize +
  78. ", pageNo=" + pageNo +
  79. ", totalPages=" + totalPages +
  80. ", totalSize=" + totalSize +
  81. ", list=" + list +
  82. '}';
  83. }
  84. }
BeanUtils复制拷贝类
  1. package com.bootdo.system.util;
  2. import java.beans.BeanInfo;
  3. import java.beans.IntrospectionException;
  4. import java.beans.Introspector;
  5. import java.beans.PropertyDescriptor;
  6. import java.lang.reflect.Field;
  7. import java.lang.reflect.InvocationTargetException;
  8. import java.lang.reflect.Method;
  9. import java.util.ArrayList;
  10. import java.util.Collection;
  11. import java.util.Date;
  12. import java.util.HashMap;
  13. import java.util.HashSet;
  14. import java.util.List;
  15. import java.util.Map;
  16. import java.util.Map.Entry;
  17. import java.util.Set;
  18. import org.apache.commons.beanutils.BeanMap;
  19. import org.apache.commons.beanutils.PropertyUtils;
  20. import org.apache.commons.lang3.StringUtils;
  21. import org.slf4j.Logger;
  22. import org.slf4j.LoggerFactory;
  23. import org.springframework.util.ClassUtils;
  24. import org.springframework.util.CollectionUtils;
  25. import com.alibaba.fastjson.JSONObject;
  26. /**
  27. * 摘要:Bean拷贝工具类
  28. * @author Williams.li
  29. * @version 1.0
  30. * @Date 2016年12月21日
  31. */
  32. public class BeanUtils extends org.apache.commons.beanutils.BeanUtils{
  33. private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);
  34. @SuppressWarnings("rawtypes")
  35. private static Map<Class, List<Field>> fieldsMap = new HashMap<Class, List<Field>>();
  36. /**
  37. * 拷贝list列表(排除Null)
  38. * @param sourceList 源列表
  39. * @param targetClass 目标class
  40. */
  41. public static <T> List<T> copyList(List<?> sourceList, Class<T> targetClass) {
  42. if(null == sourceList || sourceList.size() == 0){
  43. return null;
  44. }
  45. try{
  46. List<T> targetList = new ArrayList<T>(sourceList.size());
  47. for(Object source : sourceList){
  48. T target = targetClass.newInstance();
  49. BeanUtils.copyNotNull(target,source);
  50. targetList.add(target);
  51. }
  52. return targetList;
  53. }catch(Exception e){
  54. logger.error(e.getMessage(),e);
  55. return null;
  56. }
  57. }
  58. /**
  59. * 拷贝Object(排除Null)
  60. * @param target 目标
  61. * @param orig 源
  62. */
  63. public static <T> T copyNotNull(Class<T> targetClass, Object orig) {
  64. if( null == orig){
  65. return null;
  66. }
  67. try {
  68. T target = targetClass.newInstance();
  69. return copy(target, orig, false);
  70. }catch(Exception e){
  71. logger.error(e.getMessage(),e);
  72. return null;
  73. }
  74. }
  75. /**
  76. * 拷贝Object(排除Null)
  77. * @param target 目标
  78. * @param orig 源
  79. */
  80. public static <T> T copyNotNull(T target, Object orig) {
  81. if(null == target || null == orig){
  82. return null;
  83. }
  84. return copy(target, orig, false);
  85. }
  86. @SuppressWarnings("unchecked")
  87. public static <T> T copy(T target, Object orig, boolean includedNull, String... ignoreProperties) {
  88. if(null == target || null == orig){
  89. return null;
  90. }
  91. try {
  92. if (includedNull && ignoreProperties == null) {
  93. PropertyUtils.copyProperties(target, orig);
  94. } else {
  95. List<String> ignoreFields = new ArrayList<String>();
  96. if (ignoreProperties != null) {
  97. for (String p : ignoreProperties) {
  98. ignoreFields.add(p);
  99. }
  100. }
  101. if (!includedNull) {
  102. Map<String, Object> parameterMap = new BeanMap(orig);
  103. for (Entry<String, Object> entry : parameterMap.entrySet()) {
  104. if (entry.getValue() == null || "".equals(entry.getValue())) {
  105. String fieldName = entry.getKey();
  106. if (!ignoreFields.contains(fieldName)) {
  107. ignoreFields.add(fieldName);
  108. }
  109. }
  110. }
  111. }
  112. org.springframework.beans.BeanUtils.copyProperties(orig, target,
  113. ignoreFields.toArray(new String[ignoreFields.size()]));
  114. }
  115. return target;
  116. } catch (Exception e) {
  117. logger.error(e.getMessage(), e);
  118. }
  119. return null;
  120. }
  121. public static List<Field> getAllFields(Class<?> clazz) {
  122. if (!ClassUtils.isCglibProxyClass(clazz)) {
  123. List<Field> result = fieldsMap.get(clazz);
  124. if (result == null) {
  125. result = _getAllFields(clazz);
  126. fieldsMap.put(clazz, result);
  127. }
  128. return result;
  129. } else {
  130. return _getAllFields(clazz);
  131. }
  132. }
  133. private static List<Field> _getAllFields(Class<?> clazz) {
  134. List<Field> fieldList = new ArrayList<Field>();
  135. for (Field field : clazz.getDeclaredFields()) {
  136. fieldList.add(field);
  137. }
  138. Class<?> c = clazz.getSuperclass();
  139. if (c != null) {
  140. fieldList.addAll(getAllFields(c));
  141. }
  142. return fieldList;
  143. }
  144. /**
  145. * Get field in class and its super class
  146. *
  147. * @param clazz
  148. * @param fieldName
  149. * @return
  150. */
  151. public static Field getField(Class<?> clazz, String fieldName) {
  152. for (Field field : clazz.getDeclaredFields()) {
  153. if (field.getName().equals(fieldName)) {
  154. return field;
  155. }
  156. }
  157. Class<?> c = clazz.getSuperclass();
  158. if (c != null) {
  159. return getField(c, fieldName);
  160. }
  161. return null;
  162. }
  163. /**
  164. * 字符数组合并 注:接受多个数组参数的输入,合并成一个数组并返回。
  165. *
  166. * @param arr
  167. * 输入的数组参数,一个或若干个
  168. * @return
  169. */
  170. public static String[] getMergeArray(String[]... arr) {
  171. if (arr == null)
  172. return null;
  173. int length = 0;
  174. for (Object[] obj : arr) {
  175. length += obj.length;
  176. }
  177. String[] result = new String[length];
  178. length = 0;
  179. for (int i = 0; i < arr.length; i++) {
  180. System.arraycopy(arr[i], 0, result, length, arr[i].length);
  181. length += arr[i].length;
  182. }
  183. return result;
  184. }
  185. public static <T> T clone(Object obj, Class<T> targetClazz) {
  186. try {
  187. return copy(targetClazz.newInstance(), obj, false);
  188. } catch (Exception e) {
  189. logger.error(e.getMessage(), e);
  190. }
  191. return null;
  192. }
  193. public static <M> List<M> cloneList(List<?> srcList, Class<M> targetClazz) {
  194. return ListUtil.clone(srcList, targetClazz);
  195. }
  196. @SuppressWarnings("unchecked")
  197. public static <T> List<T> createList(T... objs) {
  198. return ListUtil.createList(objs);
  199. }
  200. /**
  201. * 功能:将bean对象转换为url参数
  202. */
  203. public static String bean2urlparam(Object obj){
  204. try{
  205. StringBuilder builder = new StringBuilder();
  206. BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
  207. PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  208. for (PropertyDescriptor property : propertyDescriptors) {
  209. String propKey = property.getName();
  210. if(!"class".equals(propKey)){
  211. Object propVal = PropertyUtils.getProperty(obj, propKey);
  212. if(propVal != null && StringUtil.isNotEmpty(propVal.toString())){
  213. builder.append(propKey).append("=").append(propVal).append("&");
  214. }
  215. }
  216. }
  217. if(builder.length() > 0){
  218. return builder.deleteCharAt(builder.length()-1).toString();
  219. }
  220. }catch(Exception e){
  221. logger.error(e.getMessage(), e);
  222. }
  223. return null;
  224. }
  225. /**
  226. * 功能:将url中的对应obj中的属性参数值替换
  227. */
  228. public static String bean2urlparam(Object obj,String param){
  229. try{
  230. BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
  231. PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  232. String newStr = param;
  233. for (PropertyDescriptor property : propertyDescriptors) {
  234. String propKey = property.getName();
  235. if(!"class".equals(propKey)){
  236. Object propVal = PropertyUtils.getProperty(obj, propKey);
  237. if(propVal != null && StringUtil.isNotEmpty(propVal.toString())){
  238. newStr = newStr.replaceAll("="+propKey,"="+propVal.toString());
  239. continue;
  240. }
  241. }
  242. }
  243. return newStr;
  244. }catch(Exception e){
  245. logger.error(e.getMessage(), e);
  246. }
  247. return null;
  248. }
  249. /**
  250. * 功能:将url中的对应obj和map中的属性参数值替换
  251. */
  252. public static String bean2urlparam(Object obj,String param,Map<String,Object> plus){
  253. try{
  254. String newParam = bean2urlparam(obj,param);
  255. if(!CollectionUtils.isEmpty(plus)){
  256. for(Entry<String,Object> entry : plus.entrySet()){
  257. Object propVal = entry.getValue();
  258. if(propVal != null && StringUtil.isNotEmpty(propVal.toString())){
  259. newParam = newParam.replaceAll("="+entry.getKey(),"="+propVal.toString());
  260. }
  261. }
  262. }
  263. if(newParam.indexOf("#") != -1){
  264. newParam = newParam.replaceAll("#","");
  265. }
  266. return newParam;
  267. }catch(Exception e){
  268. logger.error(e.getMessage(), e);
  269. return null;
  270. }
  271. }
  272. /**
  273. * 功能:将URL参数转换为map
  274. */
  275. public static Map<String,String> urlparam2map(String param){
  276. if(StringUtils.isNotEmpty(param)){
  277. Map<String,String> map = null;
  278. String[] arr = StringUtils.split(param, "&");
  279. if(arr != null && arr.length > 0){
  280. map = new HashMap<String,String>();
  281. for(String item : arr){
  282. String[] eqArr = item.split("=");
  283. map.put(eqArr[0], eqArr[1]);
  284. }
  285. return map;
  286. }
  287. }
  288. return null;
  289. }
  290. /**
  291. * 功能:将URL参数转换为JSONObject
  292. */
  293. public static JSONObject urlparam2json(String param){
  294. JSONObject paramJSON = new JSONObject();
  295. if(StringUtils.isNotEmpty(param)){
  296. String[] arr = StringUtils.split(param, "&");
  297. if(arr != null && arr.length > 0){
  298. for(String item : arr){
  299. String[] eqArr = item.split("=");
  300. paramJSON.put(eqArr[0], eqArr[1]);
  301. }
  302. }
  303. }
  304. return paramJSON;
  305. }
  306. /**
  307. * 将一个 Map 对象转化为一个 JavaBean
  308. *
  309. * @param clazz
  310. * 要转化的类型
  311. * @param map
  312. * 包含属性值的 map
  313. * @return 转化出来的 JavaBean 对象
  314. * @throws IntrospectionException
  315. * 如果分析类属性失败
  316. * @throws IllegalAccessException
  317. * 如果实例化 JavaBean 失败
  318. * @throws InstantiationException
  319. * 如果实例化 JavaBean 失败
  320. * @throws InvocationTargetException
  321. * 如果调用属性的 setter 方法失败
  322. */
  323. @SuppressWarnings("rawtypes")
  324. public static <T> T toBean(Class<T> clazz, Map map) {
  325. T obj = null;
  326. try {
  327. BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
  328. obj = clazz.newInstance(); // 创建 JavaBean 对象
  329. // 给 JavaBean 对象的属性赋值
  330. PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  331. for (int i = 0; i < propertyDescriptors.length; i++) {
  332. PropertyDescriptor descriptor = propertyDescriptors[i];
  333. String propertyName = descriptor.getName();
  334. if (map.containsKey(propertyName)) {
  335. // 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
  336. Object value = map.get(propertyName);
  337. if ("".equals(value)) {
  338. value = null;
  339. }
  340. Object[] args = new Object[1];
  341. args[0] = value;
  342. try {
  343. descriptor.getWriteMethod().invoke(obj, args);
  344. } catch (InvocationTargetException e) {
  345. logger.info("字段映射失败");
  346. }
  347. }
  348. }
  349. } catch (IllegalAccessException e) {
  350. logger.info("实例化 JavaBean 失败");
  351. } catch (IntrospectionException e) {
  352. logger.info("分析类属性失败");
  353. } catch (IllegalArgumentException e) {
  354. logger.info("映射错误");
  355. } catch (InstantiationException e) {
  356. logger.info("实例化 JavaBean 失败");
  357. }
  358. return (T) obj;
  359. }
  360. /**
  361. * 将一个 JavaBean 对象转化为一个 Map
  362. *
  363. * @param bean
  364. * 要转化的JavaBean 对象
  365. * @return 转化出来的 Map 对象
  366. * @throws IntrospectionException
  367. * 如果分析类属性失败
  368. * @throws IllegalAccessException
  369. * 如果实例化 JavaBean 失败
  370. * @throws InvocationTargetException
  371. * 如果调用属性的 setter 方法失败
  372. */
  373. public static Map<String,Object> toMap(Object bean) {
  374. Class<? extends Object> clazz = bean.getClass();
  375. Map<String, Object> returnMap = new HashMap<String, Object>();
  376. BeanInfo beanInfo = null;
  377. try {
  378. beanInfo = Introspector.getBeanInfo(clazz);
  379. PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  380. for (int i = 0; i < propertyDescriptors.length; i++) {
  381. PropertyDescriptor descriptor = propertyDescriptors[i];
  382. String propertyName = descriptor.getName();
  383. if (!propertyName.equals("class")) {
  384. Method readMethod = descriptor.getReadMethod();
  385. Object result = null;
  386. result = readMethod.invoke(bean, new Object[0]);
  387. if (null != propertyName) {
  388. propertyName = propertyName.toString();
  389. }
  390. if (null != result) {
  391. if(result instanceof Date){
  392. result = DateUtil.getDateFormat((Date)result);
  393. }else{
  394. result = result.toString();
  395. }
  396. }
  397. returnMap.put(propertyName, result);
  398. }
  399. }
  400. } catch (IntrospectionException e) {
  401. logger.info("分析类属性失败");
  402. } catch (IllegalAccessException e) {
  403. logger.info("实例化 JavaBean 失败");
  404. } catch (IllegalArgumentException e) {
  405. logger.info("映射错误");
  406. } catch (InvocationTargetException e) {
  407. logger.info("调用属性的 setter 方法失败");
  408. }
  409. return returnMap;
  410. }
  411. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/68758
推荐阅读
相关标签
  

闽ICP备14008679号