A tutorial on dynamic SQL queries for databases in the Java MyBatis Framework _java

Source: Internet
Author: User

In fact, one of the most powerful features of MyBatis is its dynamic SQL capabilities. If you have experience using JDBC or other similar frameworks, you know that it's very tangled to dynamically concatenate SQL strings together, making sure you can't forget the blanks or omit the comma at the end of the list. Dynamic SQL in MyBatis can deal with this pain thoroughly. For dynamic SQL, the easiest way to do this is to give us a sense of dynamic behavior when we hard-code it, and in MyBatis, a powerful dynamic SQL language that can be used in any mapped SQL statement. Dynamic SQL elements are similar to those using JSTL or other similar xml-based text processors. MyBatis uses powerful, OGNL-based expressions to eliminate other elements.
Several node elements we commonly use are if,choose (when, otherwise), trim (where, if), foreach. Really using it I feel a bit like XSLT (the article will incidentally mention ~) usage.
(1) Use of If

In the Viisitmapper paging configuration, if pageindex>-1 and Pagesize>-1 are added to the appropriate paging SQL, they are not added (all by default), as follows:

<select id= "Getlistbypagenate" parametertype= "Pagenateargs" resulttype= "Visitor"
  >
  select * FROM (
  <include refid= "Getlistsql"/> <include refid= "Orderbysql"/>
  ) T <!--#{} represents parameterized output, ${} indicates that direct output does not carry out any escape operations and transfers itself-->
  <if test= "pagestart>-1 and pagesize>-1" >
    Limit #{pagestart}, #{pagesize}
  </if>
</select>
<sql id= "Getlistsql" >
  SELECT * From Visitor where
  status>0
</sql>
<sql id= ' Orderbysql ' > order by
  ${ ORDERFIELDSTR} ${orderdirectionstr}
</sql>

Because our parameters pageindex and pagesize are int values, so we can directly judge, if it is an object instance we can use null judgment to carry out some dynamic logic control, the actual development of the real need to see the business needs. I think it's important to note that it's not easy to write &&, which is not recognized in the configuration.

(2) Use of choose (when, otherwise)

Choose when it is used in a scenario that satisfies only one of these conditions, such as building a query condition, passing id,name and Createtime, respectively. If we query visitor table, if VisitorID have a value, use ID query, if visitorname have a value, then use Visitname query, such as the following, Or add the list<visitor> Getlistchoosewhendemo (Basicqueryargs args) method to the David.mybatis.demo.IVisitorOperation interface class. Add the appropriate select node configuration in Visitormapper:

Package David.mybatis.demo;

Import java.util.List;
Import David.mybatis.model.BasicQueryArgs;
Import David.mybatis.model.PagenateArgs;
Import David.mybatis.model.Visitor;

Import David.mybatis.model.VisitorWithRn;
  
  Public interface Ivisitoroperation {* * * Add visitor/public int Add (Visitor Visitor);
  
  * * Delete visitor */public int delete (int id);
  
  * * Update visitor */public int update (Visitor Visitor);
  
  * * Query Visitor/Public Visitor query (int id);
  
  * * Query List */public list<visitor> getlist ();
  
  * * Paging Query List */public list<visitor> getlistbypagenate (Pagenateargs args);
  
  * * Paging query List (including rownum)/public list<visitorwithrn> Getlistbypagenatewithrn (Pagenateargs args);
  
  * * * Basic query/public Visitor basicquery (int id);
  
  * * Dynamic Conditional query (Choose,when) instance/public list<visitor> Getlistchoosewhendemo (Basicqueryargs args); * * Dynamic Conditional query (WHERE,IF) instance/public List<visitor> Getlistwheredemo (Basicqueryargs args);
  
* * Dynamic Query (foreach) instance/public list<visitor> Getlistforeachdemo (list<integer> IDs);

 }
<?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= "David.mybatis.demo.IVisitorOperation" > <resultmap type= "Visitor" id= "Visitorrs" > <id column= "id" property= "id"/> <result column= "name" property= "name"/> <result column= "Email" property = "Email"/> <result column= "status" property= "status"/> <result column= "createtime" property= "Createt"  IME "/> </resultMap> <sql id=" Getlistsqlconditions "> select * from Visitor </sql> <!-- --> <select id= "Getlistchoosewhendemo" resultmap= "Visitorrs" parametertype= "Basicque" when one of the conditions is met by choose when operation
        Ryargs "> <include refid=" getlistsqlconditions "/> <where> <if test=" Querystatus>0 "> Status=#{querystatus} </if> <choose> <when test= "queryid!=0"> and Id=#{queryid} </when> <when test=" Queryname!=null "> and name lik E #{queryname} </when> <otherwise> and createtime>= #{querytime} </oth

 erwise> </choose> </where> </select> </mapper>

(3) where if (trim) usage

The advantage of a where keyword is that if there is a corresponding filtering condition, it knows where to insert the WHERE keyword at the appropriate time. And it also knows when to remove the corresponding and and or connectors, mainly for the following scenarios

<select id= "Findactivebloglike"
   resulttype= "blog" >
 select * from Blog
 WHERE
 <if test= " State!= null ' > state
  = #{state}
 </if>
 <if test= ' title!= null ' > and
  title like #{title}< c10/></if>
 <if test= "author!= null and author.name!= null" > and
  author_name like #{author.name}< C13/></if>
</select>

Does not change because all conditions are not satisfied

<select id= "Findactivebloglike"
   resulttype= "blog" >
 select * from Blog
 WHERE
</select >

Or because the first condition is not met, the following conditions are simply met to become

<select id= "Findactivebloglike"
   resulttype= "blog" >
  select * from Blog
  WHERE and
  title like ' Sometitle '
</select>

So for this we can set the Choose when condition example, also in the Ivisitoroperation interface class add the corresponding method public list<visitor> Getlistwheredemo ( Basicqueryargs args), add the relative configuration in the Visitormapper configuration file to the following:

<?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= "David.mybatis.demo.IVisitorOperation" > <sql id= "getlistsqlconditions" > select * from Vi Sitor </sql> <!--meet the conditions are added to operate--> <select id= "Getlistwheredemo" resultmap= "Visitorrs" Parameterty Pe= "Basicqueryargs" > <include refid= "getlistsqlconditions"/> <where> <if test= "Quer"  
      Ystatus>0 "> status>0 </if> <if test=" queryid>0 "> and Id=#{queryid} 
      </if> <if test= "Queryname!=null" > and name Like=#{queryname} </if> <if test= "Querytime!=null" > and Createtime>=#{querytime} </if> </where> < !--<trim prefix= "WHERE" prefixoverrides= "and |or" > <if test= "querystatus>0"; Status>0 </if> <if test= "queryid>0" > and Id=#{queryid} </if> <i
        F test= "Queryname!=null" > and name Like=#{queryname} </if> <if test= "Querytime!=null" >

 and Createtime>=#{querytime} </if> </trim>--> </select> </mapper>

(4) The use of foreach

In a common dynamic SQL we have a business scenario where the where ID is in a large string of IDs, like this we can use foreach, do not have to work hard to stitching the ID string. The same step is to add the appropriate method to the Ivisitoroperation interface class, public list<visitor> Getlistforeachdemo (list<integer> IDs), The corresponding node element information is then configured in the corresponding mapper file, as follows:

<?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= "david.mybatis.demo.IVisitorOperation" >  
  <sql id= "Getlistsqlconditions" >
    SELECT * from Visitor
  </sql>
  <!--foreach cyclic condition-->
  <select id= " Getlistforeachdemo "resultmap=" Visitorrs ">
    <include refid=" getlistsqlconditions "/>
    where Status>0 and ID in 
    <foreach collection= "list" item= "item" index= "Index" open= "(" separator= "," close= ")" >
      ${item}
    </foreach>
  </select>
</mapper>

Finally you only need to set up the corresponding test method in the Demorun, mybatis inside the dynamic SQL is completed, the following test Demorun method

* * Dynamic Query foreach instance/public static void Getlistforeachdemo (list<integer> IDs) {sqlsession session = M
    Ybatisutils.getsqlsession ();
    Ivisitoroperation voperation = Session.getmapper (Ivisitoroperation.class);
    list<visitor> ls = voperation.getlistforeachdemo (IDS);
    for (Visitor visitor:ls) {System.out.println (Visitor); 
    }/* * Dynamic query where if instance/public static void getlistwherecondition (int id, String name, Date createtime) { Name = Name = = ""?
    Null:name;
    sqlsession session = Mybatisutils.getsqlsession ();
    Basicqueryargs args = new Basicqueryargs (ID, name, createtime);
    Ivisitoroperation voperation = Session.getmapper (Ivisitoroperation.class);
    list<visitor> ls = voperation.getlistwheredemo (args); if (ls.size () = = 0) System.out.println ("Check no match!"
    ");
      else {for (Visitor visitor:ls) {System.out.println (Visitor); }}/* * Dynamic Query Choose when instance/public STAtic void Getlistchoosewhendemo (int id, String name, Date createtime) {name = name = = ""?
    Null:name;
    sqlsession session = Mybatisutils.getsqlsession ();
    Basicqueryargs args = new Basicqueryargs (ID, name, createtime);
    Ivisitoroperation voperation = Session.getmapper (Ivisitoroperation.class);
    list<visitor> ls = voperation.getlistchoosewhendemo (args); if (ls.size () = = 0) System.out.println ("Check no match!"
    ");
      else {for (Visitor visitor:ls) {System.out.println (Visitor);

 }
    }
  }

   
PS: About OGNL
OGNL is the abbreviation for object-graph navigation Language. In terms of language: it is a powerful expression language used to get and set properties of Java objects designed to provide a higher degree of abstraction syntax for navigating Java object Diagrams, and OGNL is applied in many places, such as
as a GUI element (TextField, ComboBox, etc.) to the binding language of the Model object. The
database table to Swing's TableModel data source language.
The Binding language (Webognl,tapestry,webwork,webobjects) for Web Components and background Model objects. The
is a more expressive alternative language for Jakarata Commons beanutils or JSTL expression languages.
In addition, many of the things that can be done in Java can be done using OGNL, such as list mapping and selection. For developers, using OGNL, you can use concise syntax to complete the navigation of Java objects. Typically, a "path" is used to navigate through the object information, which can be a property of a Java bean, an object of an index in the collection, and so on, rather than using a get or set method directly.

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.