Spring + SpringMVC + MyBatis deep learning and setup (4) -- MyBatis input ing and output ing, springmvcmybatis
Reprinted please indicate the source: http://www.cnblogs.com/Joanna-Yan/p/6878529.html
I have talked about Spring + SpringMVC + MyBatis deep learning and building (3) -- MyBatis global Configuration File Parsing
1. Input ing
You can use parameterType to specify the input parameter type. The type can be simple type, hashmap, or pojo packaging type.
1.1 # {} and $ {}
#{} Sets the parameter value to the pre-processing statement in prepareStatement. In the SQL statement, #{} indicates a placeholder, that is?
<select id="findUserById" parameterType="int" resultType="user"> select * from user where id=#{id}</select>
The placeholder # {} can effectively prevent SQL injection. When used, the type of the relational parameter value is not required. mybatis will automatically convert the java and jdbc types. #{} Can receive simple type values or pojo attribute values. If parameterType transmits a single type value, the #{} brackets can be values or other names.
Different from # {}, $ {} can splice the content passed in parameterType in SQL without performing jdbc Type conversion, $ {} can receive simple type values or pojo attribute values. If parameterType transmits a single simple type value, $ {} can only contain values. Using $ {} does not prevent SQL injection, but sometimes it is very convenient to use $ {}, as shown in the following example:
<select id="findUserByName" parameterType="java.lang.String" resultType="joanna.yan.mybatis.entity.User"> select * from user where username LIKE '%${value}%' </select>
If # {} is used in this example, the input string must contain %, while % is artificially spliced in the parameter, which is obviously a little troublesome, if $ {} is used to concatenate % in SQL, it is much easier to call the mapper interface to pass parameters.
// If placeholder is used, % List <User> list = userMapper. selectUserByName ("% administrator %") must be manually added to the parameter ");
// If you use the original $ {} symbol, you do not need to manually add % List <User> list = userMapper. selectUserByName ("Administrator") to the parameter ");
For example, if order by is used to sort the column names, if the column names are passed in SQL BY parameters, the column names should be sorted by ORDER BY $ {columnName}
If # {} is used, this function cannot be implemented.
1.2 transfer simple type
Refer to the example above.
1.3 pass a pojo object
Mybatis uses an ognl expression to parse the value of an object field, as shown in the following example:
<! -- Pass the pojo object to query user information comprehensively --> <select id = "findUserByUser" parameterType = "user" resultType = "user"> select * from user where id = # {id} and username like '% $ {username} %' </select>
In SQL, the field names in the user object are marked in red.
Test:
@ Test public void findUserByUserTest () throws Exception {SqlSession sqlSession = sqlSessionFactory. openSession (); UserMapper userMapper = sqlSession. getMapper (UserMapper. class); User user = new User (); user. setId (10); user. setUsername ("Zhang San"); List <User> list = userMapper. findUserByUser (user); System. out. println (list); sqlSession. close ();}1.4 pass the pojo packaging object
In development, pojo is used to pass query conditions. query conditions are comprehensive query conditions, including not only user query conditions, other query conditions are also included (for example, the user's purchased item information is also used as the query condition). In this case, you can use the packaging object to pass the input parameters.
1.4.1 requirements
To complete the comprehensive query of user information, it is necessary to pass in complex query conditions (including user information, other information, such as goods, orders, etc)
1.4.2 define the packaging type pojo
To meet the preceding requirements, we recommend that you use a custom pojo packaging type to encapsulate complex query conditions in the pojo packaging type.
/*** Packaging type ** @ author Joanna. yan **/public class UserQueryVo {// encapsulate the required query conditions here // The user query conditions private UserCustom userCustom; public UserCustom getUserCustom () {return userCustom ;} public void setUserCustom (UserCustom userCustom) {this. userCustom = userCustom;} // other query conditions, such as orders and commodities, can be packaged //......}1.4.3 mapper. xml
Define comprehensive user information query in UserMapper. xml (complex query conditions, complex association query through advanced query)
<! -- UserCustom attribute # {userCustom is defined in UserQueryVo. sex}: Get the Gender value in the pojo packaging object $ {userCustom. username}: retrieve the user name in the pojo packaging object --> <select id = "findUserList" parameterType = "joanna. yan. mybatis. entity. userQueryVo "resultType =" joanna. yan. mybatis. entity. userCustom "> SELECT * from user where user. sex = # {userCustom. sex} AND user. username LIKE '% $ {userCustom. username} % '</select>1.4.4 mapper. java
// User information comprehensive query public List <UserCustom> findUserList (UserQueryVo userQueryVo) throws Exception;
1.4.5 test code
@ Test public void findUserListTest () throws Exception {SqlSession sqlSession = sqlSessionFactory. openSession (); UserMapper userMapper = sqlSession. getMapper (UserMapper. class); // create a packaging object and set the query condition UserQueryVo userQueryVo = new UserQueryVo (); UserCustom userCustom = new UserCustom (); userCustom. setSex ("1"); userCustom. setUsername ("Zhang Sanfeng"); userQueryVo. setUserCustom (userCustom); List <UserCustom> list = userMapper. findUserList (userQueryVo); System. out. println (list );}1.5 pass hashmap
The SQL ing file is defined as follows:
<! -- Pass hashmap to query user information comprehensively --> <select id = "findUserByHashmap" parameterType = "hashmap" resultType = "user"> select * from user where id = # {id} and username like '% $ {username} %' </select>
The key of hashmap is highlighted in red in SQL.
Mapper. java:
// Pass hashmap to query user information comprehensively
Public List <User> findUserByHashmap (HashMap <String, Object> map) throws Exception;
Test:
@ Test public void findUserByHashmapTest () throws Exception {SqlSession sqlSession = sqlSessionFactory. openSession (); UserMapper userMapper = sqlSession. getMapper (UserMapper. class); // construct the HashMap Object HashMap <String, Object> map = new HashMap <> (); map. put ("id", 10); map. put ("username", "Zhang San"); // pass the HashMap object to query the User List list <User> List = userMapper. findUserByHashmap (map); System. out. println (list); sqlSession. close ();}
When the key in the passed map is inconsistent with the key parsed in the SQL statement, no error is reported, but the value obtained through the key is null.
2. Output ing 2.1 simple output type
Take a look at the example below to output the er. xml file with an integer:
<! -- Get the total number of user lists --> <select id = "findUserCount" parameterType = "user" resultType = "int"> select count (*) from user </select>
Mapper interface:
Public interface UserMapper {// obtain the total number of User lists public int findUserCount (user User) throws Exception ;}
Test:
@ Test public void findUserCountTest () throws Exception {SqlSession sqlSession = sqlSessionFactory. openSession (); // create a UserMapper object. mybatis automatically generates the mapper proxy object UserMapper userMapper = sqlSession. getMapper (UserMapper. class); User user = new User (); user. setUsername ("yan"); // call the userMapper method int count = userMapper. findUserCount (user); System. out. println (count); sqlSession. close ();}
Summary:
The query result set contains only one row and one column. You can use a simple type for output ing.
2.2 output the pojo object and pojo list
Whether the output pojo is a single object or a list (the list includes pojo), the type specified by resultType is the same in mapper. xml.
The type of the return value of the method specified in mapper. java is different:
(1) Output a single pojo object. The return value of the method is of the single object type.
(2) The pojo Object list is output, and the return value of the method is List <POJO>
In the generated dynamic proxy object, whether to call session. selectOne (returning a single object call) or session. selectList (returning a collection object call) is determined based on the mapper method return value type ).
2.3 Summary of resultType
Use resultType for output ing. The ing is successful only when the queried column name is the same as the attribute name in pojo.
If the queried column names are inconsistent with the attribute names in pojo, no pojo object is created.
As long as the queried column name is consistent with the attribute in pojo, A pojo object is created.
2.4 output hashmap
The output pojo object can be converted to the hashmap output type. The output field name is the map key and value is the field value.
2.5 resultMap
ResultType can be used to map the query results to pojo. However, the ing can be successful only when the attribute name of pojo is the same as that of the SQL query column.
If the attribute names of SQL query fields are inconsistent with those of pojo, you can use resultMap to map the field names and attribute names. In fact, resultMap also needs to map the query results to pojo objects.
ResultMap can map query results to pojo of complex types. For example, the query result ing objects include pojo and list to implement one-to-one queries and one-to-multiple queries.
2.5.1 use of resultMap
If the queried column name is inconsistent with the attribute name of pojo, A resing relationship is defined between the column name and the attribute name of pojo by defining a resultMap.
(1) define resultMap
(2) Use resultMap as the output ing type of statement.
2.5.2 use User to map the following SQL statements
SELECT id _, username _ from user where id = # {value}
Change the SQL statement to rename the column name of the query result:
The attribute names in the User class are inconsistent with the column names in the preceding query.
2.5.2.1 define resultMap
<! -- Define resultMap to map the attributes in the SELECT id _, username _ from user and User classes. Type: the java object type finally mapped by resultMap. You can use the alias id to uniquely identify the resultMap --> <resultMap type = "user" id = "userResultMap"> <! -- Id indicates the unique column in the query result set: the queried column name, property: type, specifies the attribute name in the pojo type. The final resultMap maps the column and property (ing) --> <id column = "id _" property = "id"/> <! -- Result: defines the ing of common names column: The queried column Name property: type specifies the attribute name in the pojo type. Finally, resultMap maps the column and property (ing) --> <result column = "username _" property = "username"/> </resultMap>
2.5.2.2 use resultMap as the output ing type of statement
<! -- Use resultMap for output map: Specifies the id of the defined resultMap. If this resultMap is in another mapper file, namespace --> <select id = "findUserByIdResultMap" parameterType = "int" resultMap = "userResultMap"> SELECT id _, username _ from user where id =#{ value} </select>2.5.2.3 mapper. java
// Query User information by id and use resultMap to output public User findUserByIdResultMap (int id) throws Exception;
2.5.2.4 Test
@Test public void findUserByIdResultMapTest() throws Exception{ SqlSession sqlSession=sqlSessionFactory.openSession(); UserMapper userMapper=sqlSession.getMapper(UserMapper.class); User user=userMapper.findUserByIdResultMap(1); System.out.println(user); sqlSession.close(); }Conclusion 2.6
Use resultType for output ing. The ing is successful only when the queried column name is the same as the attribute name in pojo.
If the queried column name is inconsistent with the attribute name of pojo, A resing relationship is defined between the column name and the attribute name of pojo by defining a resultMap.
If this article is helpful to you, please let me know ~