封装MyBatis输出结果

MyBatis的输出结果:mybatis执行了sql语句,得到java对象

resultType

结果类型。

对象类型

指的是sql语句执行完毕之后,数据转为的java对象,,java类型是任意的。

处理方式:

1)mybatis执行sql语句,然后mybatis调用类的无参数构造方法,创建对象

2)mybatis把ResultSet指定列值赋给同名的属性

<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"));
}

简单类型

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

定义自定义类型的别名

1)在mybatis主配置文件中定义,使用<typeAliases>定义别名

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

2)可以在resultType中使用该别名

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

Map类型

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

resultMap

结果映射

resultMap可以自定义sql的结果和java对象属性的映射关系,更加灵活的把列值赋值给指定属性,常在列名和java对象属性名不一致的情况。

使用方式:
1)先定义resultMap,指定列名和属性名之间的对应关系

<!--配置查询所有
    使用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)在<select>中把resulType替换为resultMap

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

注意:resultType和resultMap不要一起用,二选一。 

猜你喜欢

转载自blog.csdn.net/kidchildcsdn/article/details/114164202