mapper.xml详解

1. parameterType

支持:

  • java简单类型,int,String #{占位符,任意字符}
  • pojo自定义对象 新增 #{pojo的属性名}
  • hashmap
	<!--hashmap用例
	取值方式:#{map的key}
	注意:当使用map中不存在的key取值时,取值为空null。代码不报错  -->
	<select id="selectByMap" parameterType="map" resultType="user">
		
		SELECT * FROM USER WHERE SEX= #{sex} AND address LIKE 
		concat("%",#{address},"%")
	</select>
  • 多参数的
    接口方法定义:
/**多参数用例
	 * @param sex
	 * @param address
	 */
	//public List<User> selectByParams(@Param("sex")String sex,@Param("address")String address);
	public List<User> selectByParams(String sex,String address);

xml实现:

<!--多参数用例
	parameterType可以省略
	(1).@Param:作用,把注解的对象,set放到map中去,key就是注解起的名字
	(2).使用#{index},index从0开始为第几个参数
	  -->
	<select id="selectByParams" resultType="user">
		select * from user where sex=#{0} and address like concat("%",#{1},"%")
	</select>

2. resultType

  • Java简单类型
  • pojo自定义对象类型
  • hashmap

3. resultMap

resultType::在指定pojo对象接收 映射的结果集时, 需要要将 pojo对象的属性名 和 数据库表的字段名要一致。
如果有不一致的,则查询的改字段为null
解决名字不一致的方法:
方案一

	<!--方案一: 给sql查询的字段as别名,别名和pojo对象的属性名一样  -->
	<select id="selectAll" resultType="car">
		<!-- select * from car -->
		select carId carId, name carName, userId userId from car
	</select>

方案二

	<!--
	resultMap:对应自定义的哪个resultMap的id
	  -->
	<select id="selectAll" resultMap="CarMap">
		select * from car
		select carId carId, name carName, userId userId from car
	</select>
	
	
	<!--
	type:把结果集映射到哪个对象上
	<id/>:结果集的主键唯一标识
	<result/>:结果集的普通字段
	column:表中的字段名
	property:pojo对象的属性名
	column和property:在一起表示实体类和表之间的映射关系
	  -->
	<resultMap type="car" id="CarMap">
		<id column="carId" property="carId" />
		<result column="name" property="carName" />
		<result column="userId" property="userId" />
	</resultMap>

如果使用resultMap来处理这种简单的名字不一致的问题的时候,可以在resultMap里只去配置这个名字不一致的字段(或者),名字一致的可以省略掉。

resultMap:除了能够解决上述的名字不一致的问题外,还可以解决复杂的pojo问题

	<resultMap type="UserVo" id="UserVoMap">
		<id column="id" property="id"/>
		<result column="username" property="username"/>
		<result column="sex" property="sex"/>
		<result column="birthday" property="birthday"/>
		<result column="address" property="address"/>
		<!-- 一对多 集合   ofType:集合的类型-->
		<collection property="cars" ofType="Car">
			<id column="carId" property="carId"/>
			<result column="name" property="carName"/>
			<result column="userId" property="userId"/>
		</collection>
	</resultMap>

association属性是一对一pojo使用的