Explain Mybatis in simple terms (six) input and output mapping

Input mapping parameterType:

Sometimes when we query, we pass in not only the user's information, but also some other information, such as the products purchased by the user, etc. At this time, the input parameters will contain multiple types, and we need to input the parameters. After packaging, it may return not only some information of the simple user table, but also other information. In this case, the user class needs to be extended.


Let's start with a simple example,

We need to query the user's information by the user's gender and last name.

First, you need to create a user extension class UserCustom to inherit the user class

public class UserCustom extends User{
}

Then you need to create a wrapper type UserQueryVo to wrap the input parameters

public class UserQueryVo {
    //The query conditions required for packaging are here
    //User query condition
    private UserCustom userCustom;

    public UserCustom getUserCustom() {
        return userCustom;
    }

    public void setUserCustom(UserCustom userCustom) {
        this.userCustom = userCustom;
    }
    //Can pack other query conditions, orders, commodities
}

Write our query statement in userMapper.xml.

<!-- User information comprehensive query -->
    <select id="findUserList" parameterType="userQueryVo" resultType="userCustom">
        select * from user where user.sex = #{userCustom.sex} and user.username like '%${userCustom.username}%'
    </select>

The sex here is the sex attribute of the userCustom attribute of userQueryVo, so write it like this.

Add an interface to UserMapper.

/**
     *   @author:kevin
     * @Description: Comprehensive query of user information
     *   @Date:21:18 2018/3/28
     */
    List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception;

test it

@Test
    public void testfindUserList() throws Exception{
        SqlSession sqlSession = factory.openSession();
        //Get the proxy object of UserMapper through reflection
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        UserQueryVo userQueryVo = new UserQueryVo();
        UserCustom userCustom = new UserCustom();
        //Query all users whose gender is 1 and sex Zhang
        userCustom.setSex("1");
        userCustom.setUsername("张");
        userQueryVo.setUserCustom(userCustom);
        List<UserCustom> user = userMapper.findUserList(userQueryVo);
        System.out.println(user);

    }

The console successfully outputs:


Output map:

1.resultType:

The column can be mapped successfully only if the queried column name is the same as the attribute name of the pojo.

If the queried column names and attribute names are all inconsistent, the pojo object will not be created.

As long as the queried column name has the same attribute name as the pojo, the pojo object will be created.

Let's do a test, change the query statement just now to

select id,username,addr from user where user.sex = #{userCustom.sex} and user.username like '%${userCustom.username}%'
run the test code,


It can be seen that because there is no birthday and sex in the query column, these two attributes are queried as empty.

Then modify the query statement and take an alias for id and username

select id bh,username xm,addr from user where user.sex = #{userCustom.sex} and user.username like '%${userCustom.username}%'

Run the test code again


It is found that all attributes except addr have become the initial values ​​of member variables (the object is empty, the number is 0).

Give addr an alias and try again

select id bh,username xm,addr dz from user where user.sex = #{userCustom.sex} and user.username like '%${userCustom.username}%'


At this time, we can see that because all columns are not mapped, the pojo object will not be created, and the printed result is two empty pojo objects.

Return a simple type, sometimes we need to pass a total number when paging query, then we need to return a simple type.

<!-- The total number of user information comprehensive queries-->
    <select id="findUserCount" parameterType="userQueryVo" resultType="int">
        select count(*) from user where user.sex = #{userCustom.sex} and user.username like '%${userCustom.username}%'
    </select>
/**
     *   @author:kevin
     * @Description: The total number of user information comprehensive queries
     *   @Date:21:18 2018/3/28
     */
    int findUserCount(UserQueryVo userQueryVo) throws Exception;

test


After running: the result is 2.

2.resultMap

For the problem of resultType, you can use resultMap to solve it, which can map the defined column name and attribute name.

First you need to define the sql statement.

<!-- use resultMap for output mapping
        Specify the id of the defined resultMap. If the resultMap is in another mapper file, you need to add namespace in front of it
     -->
    <select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
        select id bh,username xm,addr dz from user where id = #{value}
    </select>

Define resultMap, its id is the id in the select tag

<!-- define resultMap
        type: The final mapped java object type of resultMap, you can use an alias
        id: the unique identifier of the resultMap
     -->
    <resultMap id="userResultMap" type="user">
        <!-- id represents the unique identifier in the query result
            column: the name of the column to be queried
            The property name in the pojo type specified by property:type
            The final resultMap makes a mapping relationship between column and property
         -->
        <id column="bh" property="id"/>
        <!--
            result: mapping to normal columns
             column: the name of the column to be queried
            The property name in the pojo type specified by property:type
            The final resultMap makes a mapping relationship between column and property
         -->
        <result column="xm" property="username"/>
        <result column="dz" property="addr"/>
    </resultMap>

Add a method:

/**
     *   @author:kevin
     * @Description: Query users by id (returned using resultMap)
     *   @Date:21:18 2018/3/28
     */
    User findUserByIdResultMap(int id) throws Exception;

test:

@Test
    public void testfindUserById() throws Exception{
        SqlSession sqlSession = factory.openSession();
        //Get the proxy object of UserMapper through reflection
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.findUserByIdResultMap(1);
        System.out.println(user);

    }

Successfully output user information with id 1

User{id=1, username='kevin', birthday=null, sex='null', addr='成都'}

Here I have mapped id, username and addr, so the values ​​of these three columns are successfully output.




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325474725&siteId=291194637