Java application layer to do filtering __java

Source: Internet
Author: User

The database for some conditions of filtering support is not very good, such as like, resulting in query efficiency is not high, in practice we have designed a tool class for Java application layer filtering.

We are based on jfinal Db+record implementation.

First, a record filter is designed to determine whether a recordfilter satisfies the requirements.

Import Com.jfinal.plugin.activerecord.Record;

Import Java.util.Iterator;
Import java.util.List;
Import java.util.Objects;

/**
 * @author Xingshi 2017/01/07
 * Record Filter/
@FunctionalInterface Public
interface Recordfilter {
    /**
     * To see if a record satisfies the condition
     * @param
     is @return satisfied with
    /Boolean Accept ;
    /**
     * Filter Records
     * @param records Source records, but also filtered
     * @return The number of records to meet the conditions of the record bar/
    default list<record> Accept (List<record> Records) {
        objects.requirenonnull (records);
        Iterator<record> iterator = Records.iterator ();
        while (Iterator.hasnext ()) {The record record
            = Iterator.next ();
            Boolean acc = accept (record);
            if (!ACC) {
                //unsatisfied delete
                iterator.remove ();
            }
        }
        Return records
    }
}
Its abstract subclass Abstractrecordfilter, mainly provides some methods of judgment, in addition to better implement delete a list of remove.

Package cn.zytx.common.db.sqlfilter;

Import Com.jfinal.plugin.activerecord.Record;
Import Java.sql.Time;
Import Java.sql.Timestamp;
Import Java.util.Date;

Import java.util.List; /** * @author Xingshi 2017/01/07 * Record Filter abstract class, providing some common comparison methods * * Public abstract class Abstractrecordfilter implements record
        filter{/** * Analog like/protected Boolean attrcontains (record record,string attr,string) {
    return null!= record.getstr (attr) && record.getstr (attr). contains (except);  } protected Boolean Attrregexmatch (record record,string attr,string regex) {return null!= record.getstr (attr)
    && record.getstr (attr). Matches (regex); /** * Compare equals * * Protected Boolean attrequals (record record,string attr,string except) {return n
    ull!= record.getstr (attr) && except.equals (Record.getstr (attr)); } protected Boolean attrequals (record record,string attr,int except) {return null!= record.getint (aTTR) && except = = Record.getint (attr); } protected Boolean attrequals (record record,string Attr,long except) {return null!= Record.getlong (attr) &am
    p;& except = = Record.getlong (attr); } protected Boolean attrequals (record record,string attr,float except) {return null!= record.getfloat (attr) &
    amp;& except = = Record.getfloat (attr);  Protected Boolean attrequals (record record,string attr,double except) {return null!= record.getdouble (attr)
    && except = = Record.getdouble (attr); } protected Boolean attrequals (record record,string attr,date except) {return null!= record.getdate (attr) &am
    p;& except.gettime () = = Record.getdate (attr). GetTime (); } protected Boolean attrequals (record record,string attr,time except) {return null!= record.gettime (attr) &am
    p;& except.gettime () = = Record.gettime (attr). GetTime (); } protected Boolean attrequals (record record,string Attr,timestamp except) {return null!= record.gettimestamp (attr) && Except.compareto (Record.gettimestamp (attr)) = = 0; /** * Greater than or Equals >=,reverse is < * * Protected Boolean attrge (record Record,str
    ing Attr,int except) {return null!= record.getint (attr) && record.getint (attr) >= except; } protected Boolean Attrge (record record,string Attr,long except) {return null!= Record.getlong (attr) &AMP;&A mp
    Record.getlong (attr) >= except; Protected Boolean attrge (record record,string attr,float except) {return null!= record.getfloat (attr) &
    & Record.getfloat (attr) >= except; } protected Boolean Attrge (record record,string attr,double except) {return null!= record.getdouble (attr) &am
    p;& record.getdouble (attr) >= except; } protected Boolean Attrge (record record,string attr,date except) {return null!= record.getdate (attr) &AMP;&A mp Record.getdatE (attr). GetTime () >= except.gettime (); } protected Boolean Attrge (record record,string attr,time except) {return null!= record.gettime (attr) &AMP;&A mp
    Record.gettime (attr). GetTime () >= except.gettime (); } protected Boolean Attrge (record record,string Attr,timestamp except) {return null!= record.gettimestamp (att
    R) && Record.gettimestamp (attr). GetTime () >= except.gettime (); /** * Less than or Equals <=,reverse is > * * protected boolean Attrle (record record,string at
    Tr,int except) {return null!= record.getint (attr) && record.getint (attr) <= except; } protected Boolean Attrle (record record,string Attr,long except) {return null!= Record.getlong (attr) &AMP;&A mp
    Record.getlong (attr) <= except; Protected Boolean Attrle (record record,string attr,float except) {return null!= record.getfloat (attr) &
    & Record.getfloat (attr) <= except;
    }Protected Boolean Attrle (record record,string attr,double except) {return null!= record.getdouble (attr) &&amp ;
    Record.getdouble (attr) <= except; } protected Boolean Attrle (record record,string attr,date except) {return null!= record.getdate (attr) &AMP;&A mp
    Record.getdate (attr). GetTime () <= except.gettime (); } protected Boolean Attrle (record record,string attr,time except) {return null!= record.gettime (attr) &AMP;&A mp
    Record.gettime (attr). GetTime () <= except.gettime (); } protected Boolean Attrle (record record,string Attr,timestamp except) {return null!= record.gettimestamp (att
    R) && Record.gettimestamp (attr). GetTime () <= except.gettime (); @Override public list<record> Accept (List<record> Records) {/** * is removed from the back-forward traversal, moving elements more Less, more efficient * for (int i = Records.size ()-1; I >= 0; i--) {Boolean acc = Accept (Records.get (
            i)); if (!ACC) {records.remove (i);
    } return records; }
}
The real filtering method

Package cn.zytx.common.db.sqlfilter;
Import Com.jfinal.plugin.activerecord.Db;
Import Com.jfinal.plugin.activerecord.Page;

Import Com.jfinal.plugin.activerecord.Record;
Import java.util.ArrayList;
Import java.util.List;

Import java.util.Objects; /** * @author Xiongshiyan at 2018/1/7 * Query table data, complex filtering in the Java application layer, SQL only write very easy to filter the conditions, based on the fact that the database filtering complex conditions efficiency is not high * * public class Queryl Istwithfilter {/** * query data, incoming filters, complex filters written in the filter, SQL only write easy to filter the conditions * @param SQL SQL statements, you can write easy to filter the conditions, such as time interval this; SQL statements cannot contain? method will automatically add limit?,? to get data in batches * @param pagenumber pages * @param pageSize per page number * @param batchpulldatasize each time from the database pull the number Volume, this value to be tested optimization, each pull more can be less pull a few times, each pull to pull less on several times, need to find this balance point * @param pagetotaldatasize page can put the total number of records (based on a fact, the number of pages recorded too much, also no value), This value is degraded to a normal query if it is set to a large size. 
    This value should not be too large, or it may cause memory overflow * @param filter Java Application layer filter, more complex filtering on the Java layer to do, if passed in null, do not filter * @return page<record> * * public static page<record> query (String sql, int pagenumber, int pageSize, int batchpulldatasize, int pagetotal DataSize, Recordfilter filter) {objects.requirenonnull (SQL);
        if (Sql.touppercase (). Contains ("LIMIT")) {throw new illegalargumentexception ("SQL statement cannot contain LIMIT statement");
        SQL + + "LIMIT?,?";
        if (null = = Filter) {filter = new allacceptrecordfilter ();

        } list<record> resultlist = getrecords (sql, Batchpulldatasize, pagetotaldatasize, filter); Take out most pagetotaldatasize, not so much on the actual number of/*if (Resultlist.size () < pagetotaldatasize) {Pagetotaldatasize
        = Resultlist.size (); } resultlist = Resultlist.sublist (0,pagetotaldatasize), *///Total number of rows, int totalrow = Resultlist.s
        Ize ();
        int totalpage = totalrow/pagesize;
        if (totalrow% pageSize!= 0) {++totalpage;
        //Calculate when the page starts and ends the number int thispage = (pageNumber-1) * pageSize;
        int toindex = thispage + pageSize;
 Generally the last page is not enough if (Toindex > Resultlist.size ()) {           Toindex = Resultlist.size ();
        //Get current page Data Resultlist = resultlist.sublist (Thispage,toindex);
    return new Page<> (Resultlist, PageNumber, PageSize, Totalpage, TotalRow); /** * Multiple queries until pagetotaldatasize record is found or not enough * @param SQL SQL statement * @param batchpulldatasize per pull quantity * @ Param pagetotaldatasize page Displays the maximum number of bars * @param filter filter/private static list<record> Getrecords (String SQL, int batchpulldatasize, int pagetotaldatasize, Recordfilter filter) {list<record> resultlist = new ARR
        Aylist<> ();
        int i=0;
            while (true) {int thispage = i * batchpulldatasize;
            list<record> dataList = Db.find (sql,thispage,batchpulldatasize);
            int dbcountnumber = Datalist.size ();
            DataList = Filter.accept (dataList);
            Resultlist.addall (dataList); if (Resultlist.size () >= pagetotaldatasize | | Dbcountnumber < batchpullDataSize) {break;
        } i++;
    return resultlist; }
}
Test code:

@Test public
    void Testquerylistwithfilter () {
        String sql = ' select * from Transaction_log ';
        int pagenumber = 1;
        int pageSize = 3;
        int batchpulldatasize = 3;
        int pagetotaldatasize = 5;
        Recordfilter filter = (record)->{
            if (record.getint ("success") = = 1) {return
                true;
            }
            return false;
        page<record> query = querylistwithfilter.query (sql, pagenumber, pageSize, Batchpulldatasize, Pagetotaldatasize, filter);
        System.out.println (Query.getpagenumber ());
        System.out.println (Query.getpagesize ());
        System.out.println (Query.gettotalpage ());
        System.out.println (Query.gettotalrow ());
        list<record> list = Query.getlist ();
        List.foreach (record-> {
            System.out.println (record);}
        );
    }





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.