Mybatis的映射文件写法

Mybatis的Mapper文件


映射文件分为三个部分,头部,映射对应字段(如有必要),具体的Dao接口对应的mysql方法。
具体实例为:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.qinjing.dao.UserDao">
    <!-- 先定义一个Interface,UserMapper,然后Mapper文件的namespace指向的就是这个Interface, UserInterface里定义的方法和UserMapper.xml文件中的一样,
        然后代码里直接使用接口 -->
    <resultMap id="BaseResultMap" type="com.qinjing.pojo.User">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="username" property="username" jdbcType="VARCHAR"/>
        <result column="password" property="password" jdbcType="VARCHAR"/>
        <result column="email" property="email" jdbcType="VARCHAR"/>
        <result column="phone" property="phone" jdbcType="VARCHAR"/>
        <result column="rolename" property="rolename" jdbcType="VARCHAR"/>
    </resultMap>
    <sql id="Base_Column_List">
        id, username, password, email, phone, rolename
    </sql>
    <!--根据主键查询一条用户数据 -->
    <select id="selectByPrimaryKey" resultMap="BaseResultMap"
            parameterType="java.lang.Integer">
        select
        <include refid="Base_Column_List"/>
        from user
        where id = #{id,jdbcType=INTEGER}
    </select>
</mapper>

表头



正文部分


映射对应字段

  • id:resultMap标签的标识
  • type:返回值的全限定类名,或类型别名
  • autoMapping属性:值范围true(默认值)|false, 设置是否启动自动映射功能,自动映射功能就是自动查找与字段名小写同名的属性名,并调用setter方法。而设置为false后,则需要在resultMap内明确注明映射关系才会调用对应的setter方法。
  • constructor元素:指定使用指定参数列表的构造函数来实例化领域模型。注意:其子元素顺序必须与参数列表顺序对应
    • idArg子元素:标记该入参为主键
  • arg子元素:标记该入参为普通字段(主键使用该子元素设置也是可以的)
<select id="getStudent" resultMap="getStudentRM">
  SELECT ID, Name, Age
    FROM TStudent
</select>
<resultMap id="getStudentRM" type="EStudnet">
  <constructor>
    <idArg column="ID" javaType="_long"/>
    <arg column="Name" javaType="String"/>
    <arg column="Age" javaType="_int"/>
  </constructor>
</resultMap>

Mysql语句

  • id:代表dao接口中的方法参数名字
  • resultMap:返回参数对象(对应的映射表)
  • resultType:返回参数类型
  • #对字段加上“”,可以防止SQL注入,$直接传,不加
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值