提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
@param注解
1.含义
@Param用于dao层,是mybatis中的注解。使得mapper.xml中的参数与后台的参数对应上,也增强了可读性
区分@Param 与@RequestParam:
- @Param 是mybatis注解,@RequestParam是Springboot的注解
- @Param使用在DAO层函数,@RequestParam使用在Controlller层函数
- @Param与XML的参数关联对应,@RequestParam与html前端请求参数关联对应
2.使用场景
@ 场景一:@Param注解基本类型的参数
- mapper中的方法:
public User selectUser( @Param("userName") String name, @Param("password") String pwd );
- 映射到xml中的标签
<select id="selectUser" resultMap="User">
select * from user where user_name = #{userName} and user_password=#{password}
</select>
其中where user_name = #{userName} and user_password = #{password}中的userName和password都是从注解@Param()里面取出来的,取出来的值就是方法中形式参数 String name 和 String pwd的值。
场景二:@Param注解JavaBean对象
SQL语句通过@Param注解中的别名把对象中的属性取出来然后赋值
- mapper中的方法:
public List<User> getAllUser(@Param("user") User u);
- 映射到xml中的标签
<select id="getAllUser" parameterType="com.vo.User" resultMap="userMapper">
select
from user t where 1=1
and t.user_name = #{user.userName}
and t.user_age = #{user.userAge}
</select>
3.对象案例
- DTO
@Accessors(chain = true)
@Data
public class BadgeUpdateDTO {
/**
* 员工Id
*/
@NotNull(message = "徽章员工Id不能为空")
private Long channelId;
/**
* 徽章获取日期:yyyy-MM-dd
*/
@NotNull(message = "徽章获取日期不能为空")
private String stat_date;
/**
* 1全辖推广之星 2分行推广之星
*/
@NotNull(message = "type类型不能为空")
private Integer type;
}
- Mapper
@Repository
public interface BadgeMapper {
int updateState(@Param("dto") BadgeUpdateDTO dto);
}
- 映射到xml中的标签
<update id="updateState" parameterType="com.dto.req.BadgeUpdateDTO">
UPDATE
t_badge
SET
<if test="dto.type != null and dto.type == 1">
badge_all = 2 , update_time = CURRENT_TIMESTAMP()
</if>
<if test="dto.type != null and dto.type == 2">
badge_branch = 2 , update_time = CURRENT_TIMESTAMP()
</if>
WHERE
channel_id = #{dto.channelId} and stat_date= #{dto.stat_date}
</update>
4.注意点
- 当使用了@Param注解来声明参数的时候,SQL语句取值使用#{},${}取值都可以。
- 当不使用@Param注解声明参数的时候,必须使用的是#{}来取参数。使用${}方式取值会报错。
- 不使用@Param注解时,参数只能有一个,并且是Javabean。在SQL语句里可以引用JavaBean的属性,而且只能引用JavaBean的属性。
@Select("SELECT * from Table where id = #{id}")
Enchashment selectUserById(User user);