mapper映射文件配置之select、resultMap、resultType
<?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="Command"> <resultMap type="com.imooc.bean.Command" id="Command"> <id column="C_ID" property="id"/> <result column="NAME" property="name"/> <result column="DESCRIPTION" property="description"/> <collection resultMap="Content" property="contentList"/> </resultMap> <resultMap type="com.imooc.bean.CommandContent" id="Content"> <id column="ID" property="id"/> <result column="CONTENT" property="content"/> <result column="COMMAND_ID" property="commandId"/> </resultMap> <select id="queryCommandList" parameterType="com.imooc.bean.Command" resultMap="Command"> select a.ID C_ID,a.NAME,a.DESCRIPTION,b.ID,b.CONTENT,b.COMMAND_ID from command a left join command_content b on a.ID=b.COMMAND_ID <where> <if test="name!=null and !"".equals(name.trim())"> and NAME=#{name} </if> <if test="description!=null and !"".equals(description.trim())"> and DESCRIPTION like '%' #{description} '%' </if> </where> </select> </mapper>
select语句一般需要一个resultType或者resultMap属性,一般一对一映射时用resultType,而一对多时用resultMap
resultType:(1)表中字段和实体类中属性名完全对应,可以直接映射(2)通过select 字段 as(可省) 别名方式,使别名和实体类一致
select返回是实体类或实体类的列表,resultType都写实体类(包名+类名),或者在mybatis-config.xml文件中通过typeAliases标签配置实体类的简写
resultMap:上面的一段代码演示了一对多的配置,用的resultMap属性,通过一对多映射将字段值映射到实体类Command中,Command中又有contentList
以下是传入一个Map类型的参数,key为message和page。
<select id="queryMessageList" parameterType="java.util.Map" resultType="com.imooc.bean.Message"> select ID id,COMMAND command,DESCRIPTION description,CONTENT content from message <where> <if test="message.command!=null and !"".equals(message.command.trim())"> and COMMAND=#{message.command} </if> <if test="message.description!=null and !"".equals(message.description.trim())"> and DESCRIPTION like '%' #{message.description} '%' </if> </where> order by ID limit #{page.dbIndex},#{page.dbNumber} </select>