配置文件中有哪些标签?
在mybatis的mapper配置文件中,xml的DTD验证头部定义了元素为mapper
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
配置文件结构大致如下:
<mapper namespace="">
<resultMap id="result" type="">
<id property="id" column="id"/>
......
</resultMap>
<select id="" parameterType="List" resultMap/resultType="">
</select>
......
</mapper>
各标签的使用规则
先用具体的文件定义来说明个标签的使用规则
<mapper namespace="com.user.dao.UserDao">
//id为引用名,在用于接收数据的时候引用此resultMap
//type为引用类型
<resultMap id="user" type="com.myentity.user">
<id property="id" column="id" />
//用于配置基本数据类型字段
<result property="name" column="name" />
//用于配置引用对象字段,User对象中对应字段Phone phone,javaType定义了字段类型
<association property="phone" select="getPhone" column="{userid=id,dr=dr}" javaType="com.myentity.Phone" />
//用于配置集合对象字段,User对象中对应字段为List<String> role,ofType定义了list中的泛型,数据来自于getRoleIdList的单独查询,column设置单独查询的参数
<collection javaType="list" ofType="com.myentity.Role" property="role" select="getRoleIdList" column="{userId = id}"/>
</resultMap>
//搜索role,resultType和resultMap的区别,resultMap需要对应一个在mapper文件中定义的resultMap,而resultType则可以对应一个具体的类
<select id="getRoleIdList" parameterType="Map" resultType="com.myentity.Role">
select * from role where userId = #{userId}
</select>
//搜索phone,id对应被其他地方调用,当传入参数以key-value的形式传入的时候,parameterType需是Map类型,即使只有一个参数
<select id="getPhone" parameterType="Map" resultType="com.myentity.Phone">
select telephone
from phone
where userId = #{userId}
//trim用于连接多个and或or的查询条件
<trim prefix="where" prefixOverrides="and|or">
//if条件中需要用and或or来作为连接符号,#{param}为占位符,${param}为字符拼接
<if test="dr!=null and dr!='' ">
and dr = #{dr}
</if>
</trim>
</select>
<select id="findUser" parameterType="Map" resultMap="user">
select * from user
</select>
</mapper>