Mybatis参数映射和字段映射

时间:2020-05-27
本文章向大家介绍Mybatis参数映射和字段映射,主要包括Mybatis参数映射和字段映射使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、mybatis的参数映射不同于字段映射,参数映射中的“参数”是指传入sql语句中的参数,而字段映射是指将JDBC的结果集ResultSet数据映射成javaBean。

二、Mybatis的参数映射配置

1、Mybatis的参数映射利用的属性是 :parameterType。

parameterType,将会传入这条语句的参数的类全限定名或别名。这个属性是可选的,因为 MyBatis 可以通过类型处理器(TypeHandler)推断出具体传入语句的参数,默认值为未设置(unset)。

对于大多数的使用场景,都不需要复杂的参数,例如:

<select id="selectPeopleById" resultType="people">
    select * from people where id=#{id}
</select>
<insert id="insert" parameterType="people">
    insert into people(name, age) values (#{name}, #{age})
</insert>

2、Mybatis参数映射高级配置

#{property,javaType=int,jdbcType=NUMERIC}

三、Mybatis的字段映射配置

Mybatis中字段映射最强大的还是resultMap元素。它可以让我们从JDBC ResultSets的数据提取中解放出来。

例如下面的映射示例,其实并没有使用resultMap。

<select id="selectMapById" resultType="map">
    select id,name,age from people where id=#{id}
</select>

上述语句只是简单的将所有的列映射到HashMap的键上,这由resultType属性指定。虽然通常都够用,但是HashMap不是一个很好的领域模型。我们的程序更多的是使用javaBean或者POJO作为领域模型。Mybatis对两者都提供了支持。看看下面的javaBean:

package com.asiainfo.pojo;

public class People {
    private int id;
    private String name;
    private int age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}

上面javaBean中的3个属性:id、name和age分别对应select语句中的列名。这样的javaBean映射到ResultSet,就行映射到HashMap一样简单。

<select id="selectAll" resultType="com.asiainfo.pojo.People">
    select id,name,age from people where id=#{id}
</select

这些情况Mybatis在幕后自动创建了一个ResultMap,基于属性名映射到列到javaBean上。如果列名和属性名没有精确匹配,可以在select语句中使用别名(这是基于SQL特性)来匹配标签,比如:

<select id="selectAll" resultType="com.asiainfo.pojo.People">
    SELECT
        user_id AS id,
        user_name AS NAME,
        user_age AS age
    FROM
        people
    WHERE
        id = #{id}
</select>

下面还有一种解决列名不匹配的方式

<resultMap id="peopleResultMap" type="people">
    <id property="id" column="user_id" />
    <result property="name" column="user_name"/>
    <result property="age" column="user_age"/>
</resultMap>

而在引用它的语句中使用resultMap属性就行了(注意我们去掉了resultType属性),比如:

<select id="selectPeoples" resultMap="peopleResultMap">
    SELECT
        user_id,
        user_name,
        user_age
    FROM
        t_users
    WHERE
        id = #{id}
</select>

原文地址:https://www.cnblogs.com/wudy945/p/12976360.html