Encapsulate MyBatis output results

The output of MyBatis: Mybatis executed the sql statement and got the java object

resultType

The result type.

Object type

Refers to the java object that the data is converted to after the sql statement is executed. The java type is arbitrary.

Processing method:

1) Mybatis executes the sql statement, and then mybatis calls the parameterless construction method of the class to create the object

2) Mybatis assigns the specified column value of the ResultSet to the attribute with the same name

<select id="findAll" resultType="com.itheima.domain.User">
    select * from user
</select>
对应的jdbc
ResultSet rs = executeQuery("select * from user")
while(rs.next()){
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getName("name"));
}

Simple type

<!--    <select id="countUser" resultType="int">-->   别名
    <select id="countUser" resultType="java.lang.Integer">  全限定类名
        select count(*) from user
    </select>

Define aliases for custom types

1) Defined in the mybatis main configuration file, use <typeAliases> to define aliases

<!--定义别名-->
    <typeAliases>
            <!-- 可以指定一个类型的自定义别名
                   type:自定义类型的全限定类名
                   alias:别名(短小,容易记忆的名字)
                   -->
<!--        <typeAlias type="com.itheima.domain.User" alias="user"/>-->
<!--        第二种方式
                <package>标签:其中name是包名,表示这个包中的所有类,类名就是别名(不区分大小写)
                -->
        <package name="com.itheima.domain"/>
    </typeAliases>

2) The alias can be used in resultType

<select id="findAll" resultType="user">
    select * from user
</select>

Map type

<!--    返回Map
            1)列名是map的key,列值是map的value
            2)只能最多返回一行记录,多余一行是错误的-->
<select id="selectMapById" resultType="java.util.Map">
    select * from user where id=#{id}
</select>

resultMap

Result mapping

ResultMap can customize the mapping relationship between sql results and java object attributes, and assign column values ​​to specified attributes more flexibly. Often, column names and java object attribute names are inconsistent.

Usage:
1) Define resultMap first, and specify the correspondence between column names and attribute names

<!--配置查询所有
    使用ResultMap
    1)先定义resultMap
    2)在select标签中使用resultMap来引用1定义的
-->
<!--
    定义resultMap
    id:自定义名称,表示定义的这个resultMap
    type:java类型的全限定名称
-->
<resultMap id="userMap" type="com.itheima.domain.User">
    <!--列名和java属性的关系-->
    <!--主键列,使用id标签
        column:列名
        property:java类型的属性名
    -->
    <id column="id" property="id"/>
    <!--非主键列,使用result
        column:列名
        property:java类型的属性名
    -->
    <result column="username" property="username"/>
</resultMap>

2) Replace resultType with resultMap in <select>

<select id="findAll" resultMap="userMap">
    select * from user
</select>

Note: do not use resultType and resultMap together, choose one of the two. 

Guess you like

Origin blog.csdn.net/kidchildcsdn/article/details/114164202