Hibernate countquery strings generated by HQL, SQL

Source: Internet
Author: User
Tags assert iterable

When we write hibernate ORM component, often encounter paging query this operation, the principle of paging query is not boil, the more important point is to calculate the total number of queries count, most people still use the traditional Hql/sql string interception or splicing and other ways to achieve. The code given below is implemented by means of string templates, regular matching, and so on, directly on the code:

public class Querytemplateutil {public static final String count_query_string = ' Select COUNT (%s) from%s x '; public stat IC final String delete_all_query_string = "DELETE from%s X"; private static final String count_replacement_template = "Select COUNT (%s) $5$6$7"; private static final String Simple_count_value = "$"; private static final String Complex_count_value = "$3$6"; private static final Pattern Count_match; private static final String IDENTIFIER = "[\\p{alnum}._$]+"; private static final String Identifier_group = String.Format ("(%s)", IDENTIFIER); private static final String equals_condition_string = "%s.%s =?";  static {StringBuilder builder = new StringBuilder (); Builder.append ("(? <=from)"); From as starting delimiter builder.append ("(?:) +"); At least one space separating builder.append (identifier_group); Entity name, can is qualified (any Builder.append (": AS) *"),//exclude possible "as" keyword Builder.append ("(?:) +"); At least one space SepArating builder.append ("(\\w*)");  The actual alias builder = new StringBuilder (); Builder.append ("(select\\s+ (DISTINCT)?" (. +?)?) \\s+)?  (from\\s+ ");  Builder.append (IDENTIFIER); Builder.append ("?: \ \  \s+as) (\\s+) ");  Builder.append (Identifier_group);  Builder.append ("(. *)"); Count_match = Compile (builder.tostring (), case_insensitive);  }/** * Private constructor to prevent instantiation. */Private Querytemplateutil () {}/** * getcountquerystring: Generates a count query string based on the entity name, Count field, query criteria * <p> * <b> for example: </b>{@code entityname= "User"},{@code countqueryplaceholder= "*"}, * {@code conditionattributes=["name", "Sex"]}  , the generated countquerystring is: * </p> * <p> * {@code select COUNT (*) from User x where x.name=? and x.sex=?} * </p> * * @Title: getcountquerystring * @param entityname * Entity name, do not allow {@literal null} or {@literal empt Y} * @param countqueryplaceholder * count query placeholder field, do not allow {@literal null} or {@literal empty} * @param Conditionattri ButES * Query Criteria field * @return String */public static string Getcountquerystring (String entityname, String Countqu  Eryplaceholder, iterable<string> conditionattributes) {assert.hastext (entityname, "entity name is not allowed to be null or empty!");  StringBuilder sb = new StringBuilder (String.Format (count_query_string, Countqueryplaceholder, EntityName));  Sb.append ("WHERE"); if (conditionattributes! = null) {for (String conditionattribute:conditionattributes) {sb.append (String.Format (EQ    Uals_condition_string, "x", Conditionattribute));   Sb.append ("and");  }} sb.append ("1 = 1"); return sb.tostring (); }/** * Getcountquerystring: Generates a count query string based on the entity name * <p> * <b> Note: </b>count placeholder defaults think {@literal *}, without query criteria *   </p> * * @Title: getcountquerystring * @param entityname * Entity name, do not allow {@literal null} or {@literal empty}  * @return {@code select count (*) from Someentity x} */public static string Getcountquerystring (String entityname) { Return GetCOuntquerystring (EntityName, "*", NULL);            }/** * Getcountquerystring: Generates a count query string based on entity name, query criteria * * @Title: getcountquerystring * @param entityname * Entity name, do not allow {@literal null} or {@literal empty} * @param conditionattributes * Query Criteria field * @return {@code Select Cou NT (*) from someentity x where condition1=? and condition2=?  and 1=1} */public static string Getcountquerystring (String entityname, iterable<string> conditionattributes) { Return getcountquerystring (EntityName, "*", conditionattributes); }/** * getquerystring: Create query string by entity name and query string template * <p> * <b> See: </b>{@link Org.mk.mini.orm.util.DELETE_A ll_query_string} * </p> * * @Title: Getquerystringbytemplate * @param template * Query string template * @param  EntityName * Entity Name * @return Query String */public static string Getquerystringbytemplate (string template, String  EntityName) {Assert.hastext (entityname, "entity name is not allowed to be null or empty!"); return String.Format (template, EntiTyname);  }/** * Createcountqueryfor: Creates a count query string from the given raw SQL or HQL.  * * @Title: Createcountqueryfor * @param originalquery * Original query string, support SQL and HQL cannot be {@literal null} or {@literal Empty} * @return */public static string Createcountqueryfor (String originalquery) {Assert.hastext (originalquery, "query  The string is not allowed to be null or empty ");  Matcher Matcher = Count_match.matcher (originalquery); String variable = matcher.matches ()?  Matcher.group (4): null; Boolean usevariable = extrastringutils.hastext (variable) &&!variable.startswith ("new") &&!variable  . StartsWith ("count ("); Return Matcher.replacefirst (String.Format (count_replacement_template, usevariable?) Simple_count_value:complex_count_value)); }}

Examples do not have to write, the comments have been written very clearly, about the assert and extrastringutils just do assertion judgment and string judgment, need to copy the code of the students can be modified, write bad, please correct me.

Hibernate countquery strings generated by HQL, SQL

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.