Mybatis中对象传参及@RequestBody,@Param使用

简介:本文基于博客实体类,对在SpringBoot框架下前端传给后端参数为对象类型时的具体使用做了介绍。

提示:建议一定要仔细看红色注意部分。

SpringBoot层级运行流程基础知识介绍:

  1. 控制层接收前端请求,调用对应的业务层接口方法
  2. 业务层实现类去实现业务层接口
  3. 业务层实现类的方法内调用数据层的接口
  4. 数据层实现文件(mapper.xml)实现数据层接口
  5. 然后处理结果层层返回

下面给出了controller,mapper,mapper.xml,entity中的代码。

SpringBoot层级代码:

controller:

@GetMapping("/test")
	public R<Blog> test(@Valid @RequestBody Blog blog){
		Blog detail = service.test(blog);
		return R.data(detail);
	}

注:

  1. @Valid 注解修饰Blog参数,用于判断传入Blog是否符合规则;具体细节参考:@Valid用法详解icon-default.png?t=M85Bhttps://blog.csdn.net/weixin_43587472/article/details/110388778?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522167083157016782412549293%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=167083157016782412549293&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-1-110388778-null-null.142^v68^pc_rank_34_queryrelevant25,201^v4^add_ask,213^v2^t3_esquery_v1&utm_term=%40Valid&spm=1018.2226.3001.4187
  2. @RequestBody注解修饰Blog参数,表示前端传入controller层参数是JSON格式的字符串形式,具体细节参考:@RequestBody的使用icon-default.png?t=M85Bhttps://blog.csdn.net/justry_deng/article/details/80972817?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522167082860916782429790905%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=167082860916782429790905&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-1-80972817-null-null.142^v68^pc_rank_34_queryrelevant25,201^v4^add_ask,213^v2^t3_esquery_v1&utm_term=%40RequestBody&spm=1018.2226.3001.4187

BlogMapper:

public interface BlogMapper extends BaseMapper<Blog> {

	Blog getInfo(@Param("blog") Blog blog);
}

注:

  1. 在mapper文件中需要在getInfo方法的参数声明中加入@Param注解,这点很重要,如果不加@Param注解,但在mapper.xml中的sql语句中用到了传入的实体类中的属性参数,就会出现找不到属性字段的错误。
  2. @Param注解一定要是:package org.apache.ibatis.annotations下的注解,在使用idea代码自动提示补全功能时一定要注意,因为同一个注解在不同package中的功能是不同的,不要因为用错包导致程序出错;如果注解用错,导致的bug是很难排查的,在后期检测中会耗费掉大量时间。

BlogMapper.xml:

 <select id="test" resultType="com.fjz.screendata.entity.Blog">
        select * from blog 
        where is_deleted = 0 and id = #{blog.id}
 </select>

注:

  1. 此时blog作为传入对象,可以用对象中属性的访问方式去获取blog的id,即blog.id。
  2. 如果在xml中书写blog.id时有自动补全的提示,说明@Param注解已经在blog上生效了。

entity:

public class Blog {
	private static final long serialVersionUID = 1L;

	/**
	 * 博客id
	 */
	private String remark;

	/**
	 * 备注信息
	 */
	private String remark;

}

postman测试:

 注:

此时blog实体用body以JSON形式传入,postman传参细节参考:

postman中params传参与body传参区别icon-default.png?t=M85Bhttps://blog.csdn.net/weixin_44575911/article/details/111148852

扫描二维码关注公众号,回复: 16601368 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_44973310/article/details/128265680