Serialized form is json object, data grid submits a query with additional parameters, background uses Spring data JPA to realize conditional paging query

Keywords: Java JSON Attribute SQL P4

Many query conditions can be set in the query window

The query condition required for the load method of converting the input from the form to the DataGrid raises a new query to the original request address again and displays the results in the datagrid.

Code Annotations for Conversion Approaches

<td colspan="2"><a id="searchBtn" href="#"Class=" easyui-link button "data-options=" iconCls:'icon-search'"> query </a> 
<script type="text/javascript">
    $("#searchBtn").click(function(){
        //1,Get the query condition value to
        var condition = $("#searchForm").serializeJson();
        console.info(condition);
        //2,Submit a query with parameters, load new data from the server, including two kinds of data 1, paging needs page,rows 2,query criteria
        $('#grid').datagrid('load', condition);  
        //Close the query window
        $("#searchWindow").window("close");
    })
    
    //(Self defined JQuery Method)Make all of the items in the form name Input usage serializeArray()Method serialization form
    //Turn into  {"input Of name":"input Of value"} Of json Object form,Get a form value instead of one by one
    $.fn.serializeJson=function(){  
         var serializeObj={};  
         var array=this.serializeArray();  
         var str=this.serialize();  
         $(array).each(function(){  
             if(serializeObj[this.name]){  
                 if($.isArray(serializeObj[this.name])){  
                     serializeObj[this.name].push(this.value);  
                 }else{  
                     serializeObj[this.name]=[serializeObj[this.name],this.value];  
                 }  
             }else{  
                 serializeObj[this.name]=this.value;   
             }  
         });  
         return serializeObj;  
     }; 
</script>
</td>

Conditional paging queries in JPA are in the following interfaces

public interface JpaSpecificationExecutor<T> {  

Page<T> findAll(Specification<T> spec, Pageable pageable);

therefore

public interface CourierDao extends JpaRepository<Courier, Integer>, JpaSpecificationExecutor<Courier> {

Courier Dao inherits this interface

Pay attention to modifying generic T

Use Page < Courier > page = courierService. pageQuery (model, pageable) in the Action class; // Method with two parameters

In model, the query condition is submitted, and in pageable, page and rows are two parameters.

The code is as follows:

@Action("courierAction_pageQuery")
    public String pageQuery() throws Exception {
        Pageable pageable = new PageRequest(page, rows);
        Page<Courier> page = courierService.pageQuery(model, pageable);
        this.java2Json(page, null);
        /*Map<String, Object> map = new HashMap<>();
        map.put("total", page.getTotalElements());
        map.put("rows", page.getContent());
        
        //Exclude the set attribute fixedAreas in the courier object (ignore this attribute, and eventually no attribute exists in the courier object)
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[]{"fixedAreas", "company"});
        
        String json = JSONObject.fromObject(map, jsonConfig).toString();
        System.err.println(json);
        ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
        ServletActionContext.getResponse().getWriter().write(json);*/
        return NONE;
    }

But the first parameter type required by the conditional paging query method is Specification < T > spec as follows

Page<T> findAll(Specification<T> spec, Pageable pageable);

So code

courierService.pageQuery(model, pageable)

Specification objects are generated according to the model in the service implementation class to invoke methods in the interface

return courierDao.findAll(spec , pageable);

The object generation method is as follows:

public Page<Courier> pageQuery(final Courier model, Pageable pageable) {
    //Encapsulating query objects Specification
    Specification<Courier> spec = new Specification<Courier>() {
        
        //Encapsulated query conditions: sql: select * from t_courier where Column 1 = ? and|or Column 2 like ?
        //Parametric 1: root entity, representative Criteria The root object of the query, Criteria The query root of the query defines the entity type, which can provide the desired results for future navigation. SQL Query FROM Similar clause
        //Parametric 2: Represents one specific The top-level query object, which contains various parts of the query, such as: select ,from,where,group by,order by etc.
        //Parametric 3: Used to build CritiaQuery Constructor object--produce Predicate(Assertion) instance factory
        public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            
            List<Predicate> list = new ArrayList<>();
            //Parametric 1: Get attributes (columns in tables) from the root entity by navigating
            //Parametric 2: Query value
            String courierNum = model.getCourierNum();
            String company = model.getCompany();
            String type = model.getType();
            if(StringUtils.isNotBlank(courierNum)){
                //. . . .  where c_courier_num = ?
                Predicate p1 = cb.equal(root.get("courierNum").as(String.class), courierNum);
                list.add(p1);
            }
            if(StringUtils.isNotBlank(company)){
                // +condition c_company = ?
                Predicate p2 = cb.equal(root.get("company").as(String.class), company);
                list.add(p2);
            }
            if(StringUtils.isNotBlank(type)){
                // +condition c_type = ?
                Predicate p3 = cb.equal(root.get("type").as(String.class), type);
                list.add(p3);
            }
            //Relational query
            Standard standard = model.getStandard();
            if(standard!=null){
                String standardName = standard.getName();
                if(StringUtils.isNotBlank(standardName)){
                    //Creating Associated Objects :Standard Acquiescence: JoinType.INNER Internal connection
                    Join<Object, Object> join = root.join("standard", JoinType.INNER);
                    //Query attributes in associated objects
                    Predicate p4 = cb.like(join.get("name").as(String.class), "%"+standardName+"%");
                    list.add(p4);
                }
            }
            if(list.size()==0){
                return null;    
            }
            Predicate [] predicates = new Predicate[list.size()];
            //take list Combining the existence of assertion objects in an array predicates
            predicates = list.toArray(predicates);
            
            // cb.and Equivalent to query condition usage and Splicing--also
            // cb.or Equivalent to query condition usage or Splicing   --perhaps
            return cb.or(predicates);
        }
    };
    return courierDao.findAll(spec , pageable);
}

String Utils isorg.apache.commons.lang3 Tool class under. StringUtils package

There are several values of the assertion.

When splicing, you need to provide an array of assertions

return cb.or(predicates );

The array is fixed length, and we are not sure how many assertions there are.

So you can only create an array of variable length, so you need to set the length of the array to use a variable, using list.size()

Predicate [] predicates = new Predicate[list.size()];

Use its toArray() method to convert a collection to an array of a specified type, without tragedy to Object [], with parameters to an array of a specified type

predicates = list.toArray(predicates);

If there is no additional condition, it is a normal paging query.

            if(list.size()==0){
                return null;    
            }

Then

return courierDao.findAll(spec , pageable);

spec is empty.

Posted by keveen on Fri, 11 Jan 2019 11:06:10 -0800