MyBatis dynamic SQL (where element, set element, if element)

Source: Internet
Author: User

MyBatis dynamic SQL (where element, set element, if element)

-the Where element only inserts a "where" clause if the condition of at least one child element returns a SQL clause. Also, if the statement begins with "and" or "or", thewhere element will also remove them.

(That is, where it is used in a query with multiple if conditions, it also filters out the start of the statement and, or)

-if element can make a judgment on the given object again

-The set element can be used to dynamically include columns that need to be updated, and to remove the other.

1. Create a dynamic SQL for search

(1), add the following select tag to the mapping of the configuration file corresponding to the table (then it will empty the element first when it is found)

1     <SelectID= "Search"Resultmap= "UserMap">2 SELECT * from USR13         <where>4             <ifTest= "Username!=null">5 and Username=#{username}6             </if>7             <ifTest= "Password!=null">8 and Password=#{password}9             </if>Ten         </where> One     </Select>

(2), add the following code in the Main method, (load the corresponding configuration file, query user name GetChar, password is 1234 of the existence of the user, this judgment is often useful in user login)

1Config = Resources.getresourceasstream ("Mybatis-config.xml");2Sqlsessionfactory factory =NewSqlsessionfactorybuilder (). build (config);3 4sqlsession session =factory.opensession ();5Userdao Userdao = Session.getmapper (Userdao.class);6User U =NewUser ();7U.setpassword ("1234");8U.setusername ("GetChar");9list<user> users =userdao.search (u);Ten System.out.println (Users.size ()); OneSystem.out.println (users);

(3), so that the implementation of the query, you can realize that the password and account is empty

MyBatis dynamic SQL (where element, set element, if element)

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.