Serialized form as JSON object, DataGrid with additional parameters submit once query background using spring data JPA to implement a paged query with conditions

Source: Internet
Author: User
Tags array length

Many query conditions can be set in the query window

The input from the form to the query criteria required by the Load method of the DataGrid presents a new query to the original request address, displaying the results in the DataGrid

Conversion method See code comment

&LT;TD colspan= "2" ><a id= "searchbtn" href= "#" class= "Easyui-linkbutton" data-options= "IconCls: ' Icon-search '" > Enquiry </a> <script type= "Text/javascript" >    $("#searchBtn"). Click (function(){        //1. Get the query condition value to        varCondition = $ ("#searchForm"). Serializejson ();        Console.info (condition); //2, with the parameter to submit a query, loading new data from the server including two kinds of data 1, paging needs page,rows 2, query conditions$ (' #grid '). DataGrid (' Load ', condition); //Close the Query window$ ("#searchWindow"). Window ("Close"); })        //(custom jquery method) serializes the form using the Serializearray () method for all input items that have name in the form    //into the JSON object form of {"Input name": "Value of Input"}, instead of getting a single form value$.fn.serializejson=function(){           varserializeobj={}; vararray= This. Serializearray (); varStr= 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;           }           }); returnSerializeobj; }; </script></td>

JPA with conditional paging queries in the following interface

Public interface Jpaspecificationexecutor<t> {

Page<t> FindAll (specification<t> spec, pageable pageable);

So

Public interface Courierdao extends Jparepository<courier, integer>, jpaspecificationexecutor<courier> {

Courierdao to inherit the interface

Note Modify the generic T

The Action class uses page<courier> page = Courierservice.pagequery (model, pageable);//method with two parameters

The model is the submitted query condition, which is page and rows two parameters in pageable

The code is as follows:

@Action ("Courieraction_pagequery")     PublicString Pagequery ()throwsException {pageable pageable=Newpagerequest (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 ());        Excludes the collection attribute Fixedareas in the Courier object (ignoring the attribute and ultimately the Courier object does not exist) 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);*/        returnNONE; }

But the method with conditional paging query requires the first parameter type of specification<t> spec as follows

Page<t> FindAll (specification<t> spec, pageable pageable);

So the code

Courierservice.pagequery (model, pageable)

In a service implementation class to generate specification objects based on model to invoke methods in the interface

Return Courierdao.findall (spec, pageable);

The resulting object method is as follows:

 PublicPage<courier> Pagequery (FinalCourier model, pageable pageable) {    //encapsulates a Query object specificationSpecification<courier> spec =NewSpecification<courier>() {                //Package Query Condition: Sql:select * from t_courier where column 1 =? and|or column 2 like? //parameter one: the root entity, which represents the root object of the criteria query, and the query root of the criteria query defines the entity type, which can obtain the desired result for future navigation, similar to the FROM clause in the SQL query//parameter two: represents a specific top-level query object, which contains the various parts of the query, such as: Select, from, where, group by, and order BY, etc.//parameter three: Builder object used to build critiaquery--generate predicate (Assert) instance factory         Publicpredicate topredicate (root<courier> Root, criteriaquery<?>query, Criteriabuilder CB) {List<Predicate> list =NewArraylist<>(); //parameter one: Get properties by navigation from the root entity (columns in the table)//parameter two: query valueString 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); }            //Correlation QueryStandard =Model.getstandard (); if(standard!=NULL) {String StandardName=Standard.getname (); if(Stringutils.isnotblank (StandardName)) {//Create an association object: standard Default: Jointype.inner internal connectionJoin<object, object> join = Root.join ("Standard", Jointype.inner); //querying properties in associated objectspredicate P4 = Cb.like (Join.get ("name"). As (String.class), "%" +standardname+ "%");                List.add (p4); }            }            if(List.size () ==0){                return NULL; } predicate [] predicates=Newpredicate[list.size ()]; //The list is combined with the assertion object in the array predicatespredicates =List.toarray (predicates); //Cb.and equivalent to query conditions using and stitching--and//cb.or equivalent to query conditions using or stitching--or            returncb.or (predicates);    }    }; returnCourierdao.findall (spec, pageable);}

StringUtils for org.apache.commons.lang3.StringUtils under the tool class

Where the asserted value has several

You need to provide an array of assertions when stitching

return cb.or (predicates);

And the array is fixed, and we're not sure how many assertions

So you can only create a variable-length array, then you need to set the array length using a variable, using list.size ()

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

Converts a collection into an array of the specified type using its ToArray () method, without any tragic conversion to object[], with arguments to an array of the specified type

predicates = List.toarray (predicates);

If there is no additional condition, it is a normal paged query

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

Then

Return Courierdao.findall (spec, pageable);

Spec is empty

Serialized form as JSON object, DataGrid with additional parameters submit once query background using spring data JPA to implement a paged query with conditions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.