MyBatis的mapping.xml中有两个重要的属性:parameterType和resultMap属性(parameterMap现在不建议使用)
parameterType用来指定传入参数的类型,比如Bean或Map\List。
<configuration> <typeAliases> <typeAlias alias="Product" type="com.zainagou.supplier.entity.Product"/> </typeAliases> <!-- 映射map --> <mappers> </mappers> </configuration>
resultMap是MyBatis中最重要最强大的元素。resultMap封装查询的结果集,type可以是Bean、Object、Primitive type。
<?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.zainagou.supplier.mapper.ProductCategoryMapper"> <parameterMap id="productCategory" type="com.zainagou.supplier.entity.ProductCategory"></parameterMap> <resultMap id="resultMap" type="com.zainagou.supplier.entity.ProductCategory" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="p_id" property="pid" jdbcType="INTEGER" /> <result column="name" property="name" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > id, fid, name </sql> <select id="getProductCategorys" resultMap="resultMap" parameterMap="productCategory"> select <include refid="Base_Column_List" /> from product_category where 0=0 <if test="name!=null and name!=''"> and name like "%"#{name,jdbcType=VARCHAR}"%" </if> </select> </mapper>
从上面mapping.xml可以看出:
resultMap中, column是列名,property是列映射到实体对象的属性,jdbcType是列在数据库中的数据类型,格式统一都是大写,和MySql中的数据类型多数保持一致,少数有差异。
这种方式可以解决列名不匹配。