MyBatis using dynamic SQL on annotations (@select using IF)

Source: Internet
Author: User

1. script Surround with tags and write like XML syntax

@Select ({"<script>",    "select * from Tbl_order",        "WHERE 1=1", "< When test= ' title!=null ' > ',    ' andmydate = #{mydate}    ', ' </when> ',    "</script>"})

2, use Provider to achieve SQL splicing, for example:

 Public classOrderprovider {Private FinalString Tbl_order = "Tbl_order";  PublicString queryorderbyparam (orderpara param) {SQL SQL=NewSQL (). Select ("*").        From (Tbl_order); String=Param.getroom (); if(Stringutils.hastext ()) {SQL. WHERE ("#{room}"); } Date mydate=param.getmydate (); if(MyDate! =NULL) {sql. WHERE ("MyDate like #{mydate}"); }        returnsql.tostring (); }} Public InterfaceOrderdao {@SelectProvider (type= Orderprovider.class, method = "Queryorderbyparam") List<Order>queryorderbyparam (Orderparam param);}

Note: One of the pitfalls of mode 1 is that when an incoming parameter is empty, it may cause a full table query.

Complex SQL 2 is more flexible (of course, it is not recommended to write complex SQL), and can be abstracted into a common base class, so that each DAO can implement basic generic queries through this base class, similar in principle Spring JDBC Template .

Reference:

https://segmentfault.com/q/1010000006875476 (the above content is transferred from this answer)

https://stackoverflow.com/questions/6685655/ How-to-use-dynamic-sql-query-in-mybatis-with-annotationhow-to-use-selectprovide

MyBatis using dynamic SQL on annotations (@select using IF)

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.