Mybatis的传参注意点(单参数、多参数、复杂参数)
1. 传入参数为List
mapper接口:
List<User> getUserList(List<Long> list);
mapper映射文件:List用foreach
去遍历
如果查询的实体类的参数和数据库中的字段名不一致,要用resultMap
进行映射
<select id="getUserList" resultMap="UserResultMap" parameterType="List">
select * from user_info where id in
(
<foreach collection="list" item="item" separator=",">
#{item}
</foreach>
)
</select>
resultMap映射:column:数据库中的字段名,property:实体类中的属性名
<resultMap id="UserResultMap" type="User">
<!-- 定义主键 ,非常重要。如果是多个字段,则定义多个id -->
<!-- property:主键在pojo中的属性名 -->
<!-- column:主键在数据库中的列名 -->
<id column="user_id" property="id" jdbcType="BIGINT"/>
<!-- 定义其他属性 -->
<result property="name" column="user_name" jdbcType="VARCHAR"/>
<result property="createTime" column="create_time" jdbcType="DATE"/>
<resul property="updateTime"t column="update_time" jdbcType="DATE"/>
</resultMap>
javaType和jdbcType的对应表:
2. 传入多个不同类型参数
mapper接口:
void updateAlarmInfo(@Param("user") User user,@Param("id") Long id);
mapper映射文件:传入多个参数时,parameterType不用写,在接口上写上参数的注解
<update id="updateUser" >
update market_channel_alarm_info
set update_time = sysDate(),
name = #{user.name},
status = '0'
where id=#{id}
</update>
3. useGeneratedKeys和keyProperty的使用:
当主键是自增的情况下,添加一条记录的同时,其主键是不能使用的,但是有时我们需要该主键,这时我们只需要在其对应xml中加入以下属性即可:
useGeneratedKeys=“true” keyProperty=“对应的主键的对象”。
useGeneratedKeys这个只在insert语句中有效,当useGeneratedKeys为true时,如果插入的表id以自增列为主键时,将会把该自增id返回。例如:
<!-- 在主键是自增的情况下,添加成功后可以直接使用主键值,其中keyProperty的值是对象的属性值不是数据库表中的字段名-->
<insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO market_channel_info(`user_name`, `user_gender`, `user_age`)
VALUES(#{name}, #{gender}, #{age})
</insert>
这样在之后的java代码中我们就可以获取该主键对应的对象的属性值(id)