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>
表头
- <?xml version="1.0" encoding="UTF-8" ?> 说明xml的版本是1.0,编码格式为UTF-8。
- <DOCTYPE mapper PUBLIC “-//mybatis.org//DTD Mapper 3.0//EN” “http://mybatis.org/dtd/mybatis-3-mapper.dtd”> 则表示此xml文件所对应的命名空间
正文部分
映射对应字段
- 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注入,$直接传,不加