The dynamics of Hibernate sql-query (SQL/HQL) is achieved through velocity templates

Source: Internet
Author: User
Tags scalar

A Brief introduction

Hibernate provides a more complete encapsulation of the database structure, and Hibernate's O/R mapping implements the mapping between Pojo and database tables, as well as the automatic generation and execution of SQL. While MyBatis is an excellent persistence layer framework that supports plain SQL queries, stored procedures, and advanced mappings, MyBatis needs to use simple XML or annotations for configuration and raw mapping, and the interface and Java Pojo (Plain old Java Objects, Common Java objects) are mapped to records in the database. When writing more complex dynamic SQL statements, MyBatis's SQL is written manually, so you can specify the fields of the query as required, and hibernate is a difficult implementation.

Two The idea of solving the problem mybatis the excellent persistence layer framework that supports plain SQL queries, stored procedures, and advanced mappings, MyBatis needs to use an XML configuration that will interface and Java Pojo (Plain old Java Objects, Common Java Objects) mapped to records in a database, let's look at what MySQL does with dynamic SQL statements, such as:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mapper namespace= "Cn.social.card.mybatis.persistence.SocialSecurityCardMapper" > <resultmap id= " Baseresultmap "type=" Cn.social.card.mybatis.domain.SocialSecurityCard "> <id column=" id "jdbctype=" DECIMAL " property= "id"/> <result column= "pch" jdbctype= "VARCHAR" property= "pch"/> <result column= "DWBH" JdbcTyp e= "varchar" property= "DWBH"/> <result column= "XM" jdbctype= "varchar" property= "XM"/> <result column= "X B "jdbctype=" varchar "property=" XB "/> <result column=" Sfzh "jdbctype=" varchar "property=" Sfzh "/> <resu Lt column= "Sbkh" jdbctype= "varchar" property= "Sbkh"/> <result column= "DWMC" jdbctype= "varchar" property= "DWMC"/ > <result column= "yhkh" jdbctype= "varchar" property= "Yhkh"/> <result column= "swkzt" jdbctype= "varchar" Property= "Swkzt"/> <result column= "JSDWLXR" jdbctype= "VARCHAR" property= "JSDWLXR"/> <result column= "JSDWLXDH    "jdbctype=" varchar "property=" JSDWLXDH "/> <result column=" djckry "jdbctype=" varchar "property=" Djckry "/> <result column= "Djcklxfs" jdbctype= "VARCHAR" property= "Djcklxfs"/> <result column= "Djssdw" jdbcType= "VARCHA R "property=" Djssdw "/> <result column=" Czry "jdbctype=" VARCHAR "property=" Czry "/> <result column=" CZRQ "Jdbctype=" VARCHAR "property=" Czrq "/> </resultmap><select id=" Findcountbycriteria "resultType="     Java.lang.Integer "> select COUNT (*) from T_social_card T1 <include refid=" Find_where "/> </select> <select id= "Findpagelistbycriteria" resultmap= "Baseresultmap" > <include refid= "detail_select"/> &lt  Include refid= "Find_where"/> </select> <sql id= "Find_where" > Where 1=1 <if test= "param ! = NULL "> and (T1. Sfzh LIKE '% ' +#{param}+ '% ' OR T1. XM like '% ' +#{param}+ '% ') </if> </sql> </mapper>

Resultmap need to put a field configuration, if a table fields too much display is very bloated and easy to configure error, let's leave this, let's see how MyBatis implemented Dynamic SQL, using the IF, foreach tags, before executing the SQL statement, Parse these tags first.

We also have a template engine on the page, built in a lot of common methods of Web programming (date conversion, digital formatting, etc.) to facilitate the developer's operation. More commonly, freemarker is a template engine, a template-based generic tool for generating output text, which is based on Java's development packages and class libraries. We can learn from MyBatis to realize the idea and adopt the template engine.

To introduce you to another velocity,velocity is a Java-based template engine (Templateengine). It allows anyone to refer to objects defined by Java code simply by using template language (language). It can generate SQL and PostScript, XML from Templates (template), and it can also be used as a standalone tool to generate source code and reports, or as an integration component of other systems. Velocity can also provide template services for the turbine Web development architecture.

Three The sql-query dynamic SQL 1 is implemented through velocity. First introduce the structure of the project, so that the idea will be more clear



2. Implement the Hbm.xml configuration

<?xml version= "1.0"?> <! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ HIBERNATE-MAPPING-3.0.DTD "><!--mapping file autogenerated by Myeclipse-hibernate Tools---

Velocity is identified by "#", such as #set, #if, #else, #end, #foreach, #end, #iinclude, #parse, #macro等;

For example:

#if ($XM)

and T.XM=:XM

#end

#if ($PCH)

And t.pch like '% $pch% '

#end


Implementation of 3.JAVA Code

(a) Carddaoimpl

@Repositorypublic class Carddaoimpl extends basedaoimpl<card> implements Carddao {@SuppressWarnings ("unchecked" ) @Overridepublic list<card> getcards (map<string, object> param) {return getnamedquery ("Card.getcards", param). Setresulttransformer (Transformers.aliastobean (Card.class)). List ();}}

(ii) Basedaoimpl

public class Basedaoimpl<t> implements basedao<t> {@Autowiredprivate sessionfactory sessionfactory;public Session getcurrentsession () {return sessionfactory.getcurrentsession ();} @Overridepublic void Add (Object Entriy) {getcurrentsession (). Save (Entriy);} /** * Set Dynamic SQL * @param queryname * @param param * @return * * * @SuppressWarnings ("rawtypes") public Query getnamedquery (strin G queryname,map<string,object> param) {Query query=getcurrentsession (). Getnamedquery (QueryName); Query Rsquery=null;try {//initializes the run-time engine, initializes the Velocity.init () by default,//establishes the context and puts the data velocitycontext context=new Velocitycontext (); Set<string> Keys=param.keyset (); for (Iterator Iterator = Keys.iterator (); Iterator.hasnext ();) {String key = (string) iterator.next (); Context.put (Key, Param.get (key));} After parsing the output target of the data, Java.io.Writer subclass StringWriter Sql=new StringWriter ();//Parse Velocity.evaluate (context, SQL, "Myquery", Query.getquerystring ()); Rsquery=getcurrentsession (). Createsqlquery (Sql.tostring ());} catch (ExcEption e) {e.printstacktrace ();} Setquerynameparameters (Rsquery,param); return rsquery;} /** * Set Parameters * @param query * @param param * @return */public query setquerynameparameters (query query,map<string,object&  Gt param) {string[] nameparams=query.getnamedparameters (); for (String nameparam:nameparams) {Object Obj=param.get ( Nameparam); if (obj instanceof Collection) {query.setparameterlist (Nameparam, (Collection) obj);} else if (Obj.getclass (). IsArray ()) {Query.setparameterlist (Nameparam, (object[]) obj);} Else{query.setparameter (Nameparam,obj);}} return query;}}


is to parse the template by velocity template and the parameters parameter passed in, and get the final statement (pure SQL/HQL).

1) Get the most original SQL statement query Query=getcurrentsession (). Getnamedquery (QueryName);

2) The template is parsed by the Velocity template and the parameters parameters passed in, velocity.evaluate (context, SQL, "Myquery", query.getquerystring ());

3) then re-create the SQL/HQL statement, Rsquery=getcurrentsession (). Createsqlquery (Sql.tostring ());

4) Set the parameter value and execute the return result











Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The dynamics of Hibernate sql-query (SQL/HQL) is achieved through velocity templates

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.