Mybatis Practical Article (iii) parameter processing
The parameter parametertype in the SQL statement can be omitted from the write.
I. Parameter encapsulation 1.1 single parameter processing
public interface UserMapper { User getUser(int id);}
The value of #{} in SQL can be arbitrary, mybatis do not do any processing, eg:
<select id="getUser" parameterType="int" resultType="User"> select * from user where id=#{xxx};</select>
1.2 + parameter Handling
Multiple parameters MyBatis encapsulated into a Map, the default parameter of key is param1, param2 ..., you can also use the @Param ("id") to specify the value of key
User getUser(@Param("id") int id, String name);
SQL can have the following wording:
<select id="getUser" resultType="User"> <!--select * from user where id=#{0} and name=#{1};--> <!--select * from user where id=#{param1} and name=#{param2};--> <!--select * from user where id=#{0} and name=#{param2};--> select * from user where id=#{id} and name=#{param2};</select>
1.3 Java Bean
User getUser(User user);
SQL can have the following wording:
<select id="getUser" resultType="User"> select * from user where id=#{id} and name=#{name};</select>
1.4 Map
User getUser(User user);
SQL can have the following wording:
<select id="getUser" resultType="User"> select * from user where id=#{id} and name=#{name};</select>
Thinking:
User getUser(@Param("id") int id, String name);id ==> #{id/param1/0} name ==> #{param2/1}User getUser(int id, @Param("user") User user);id ==> #{id/param1/0} name ==> #{param2.name/user.name}# Collection ==> list, Array ==> array. eg: 取出 list 中的第一个值User getUser(List<User> users);id ==> #{list[0]}
Two, #{} and ${} differences
#{}Precompiled, and ${} only string stitching.
In actual work, try to use #{}, special occasions need to use ${}, such as:
select * from ${tablename}
Three, #{} parameters
The MyBatis value is null when the default corresponds to TYPES in the database. Ohter, you can modify the global configuration:
Record a little bit every day. Content may not be important, but habits are important!
Mybatis Practical Article (iii) parameter processing