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)