組合查詢--表單對象轉化為json對象

來源:互聯網
上載者:User

標籤:lan   get   string   轉換   ext   action   hashmap   ati   .class   

//1.將page和rows封裝到pageable中
  Pageable pageable = new PageRequest(page, rows);
  //2.建立組合條件查詢條件對象
  Specification<FixedArea> spec = new Specification<FixedArea>() {

   @Override
   public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    //2.1建立存放已拼裝條件的list集合
    ArrayList<Predicate> predicates = new ArrayList<Predicate>();
    
    //2.2進行組合查詢條件的拼裝
    String id = model.getId();
    if(StringUtils.isNotBlank(id)){
     
     predicates.add(cb.equal(root.get("id").as(String.class), id));
     
    }
    String company = model.getCompany();
    if(StringUtils.isNotBlank(company)){
     
     predicates.add(cb.like(root.get("company").as(String.class), "%"+company+"&"));
     
    }
    
    //2.3建立存放拼裝條件的predicate數組
    Predicate[] predicateArr = new Predicate[predicates.size()];

    //2.4返回拼裝好的條件
    return query.where(predicates.toArray(predicateArr)).getRestriction();
   }
  };
  
  //3.執行分頁查詢
  Page<FixedArea> page = fixedAreaService.pageQuery(spec,pageable);
  
  //4.去除會造成no session 的 FixedArea實體類中的"many"欄位
  String[] excludes = { "subareas", "couriers" };
  
  //調用baseAction中的方法將查詢到的結果轉化成json發送到前台
  this.write2JsonObject(page, excludes);

-------------------------------------------------------------------------------------------------------------

baseAction中:

public void write2JsonObject(Page<?> page, String[] excludes) throws IOException {

  // 構建json對象型資料
  Map<String, Object> map = new HashMap<String, Object>();
  map.put("total", page.getTotalElements());
  map.put("rows", page.getContent());

  // JsonConfig: 配置轉換的json資料中不需要的屬性
  JsonConfig jsonConfig = new JsonConfig();

  jsonConfig.setExcludes(excludes);

  // 將map轉化為json
  String json = JSONObject.fromObject(map, jsonConfig).toString();
  ServletActionContext.getResponse().setContentType("test/json;charset=UTF-8");
  ServletActionContext.getResponse().getWriter().print(json);

 }

組合查詢--表單對象轉化為json對象

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.