springboot中mapper和controller的关系,新手实例(有误待查)

以获取用户发送的json数据,并返回同样的数据为例,讲解@RequestMapping的用法以及mapper和controller的关系

UserController中可以使用@RequestMapping捕获数据请求,以实例化构造方法的方式来对数据进行处理和response

@RequestMapping(value = "/test",produces="application/json")
//构造方法 这个方法是UserController类中的一个方法,跟mapper类没有关系
public String getUserRequest(@RequestBody String jsonString){
    return jsonString;
}

在一般情况下,都需要mapper对数据进行处理以及反馈。比如数据库的操作,以及返回相应的数据。
这时候 需要注入一个实例化对象,以这个实例化对象调用方法的方式完成操作步骤。

2.5前注入方式:

  @Override
  private UserTestMapper userTestMapper;

2.5后官方推荐的方式:

final private UserTestMapper userTestMapper;
    public UserController(UserTestMapper userTestMapper) {
        this.userTestMapper = userTestMapper;
    }

这时候就会需要用到mapper接口,创建一个mapper接口(Interface)UserTestMapper声明一个你需要的方法。同时在mapper目录下impl文件夹中创建mapper的实现UserTestMapperImpl。因为mapper文件夹会被自动获取,interface中只保留接口能降低资源占用。在调用interface中的方法时候,就可以找到对应的implement。所以mapper目录下放接口,子目录中放这些接口的实例。

package com.neo.mapper;
public interface UserTestMapper {
    String getJsonReturnHello(String json);
}
package com.neo.mapper.impl;
import com.neo.mapper.UserTestMapper;
import org.springframework.stereotype.Component;

@Component
public  class UserTestMapperImpl implements UserTestMapper {
    @Override
    public String getJsonReturnHello(String json) {
        return "hello!";
    }
}

这时候就可以在controller构造mapper中声明的方法主体了

@RequestMapping(value = "/getJsonTest2",produces = "application/json")
// @RequestBody可以获取用户request的主体
public String getUserTestMapper(@RequestBody String jsonString){
    return jsonString;
}

这样就可以在Controller中进行调用UserTestMapper创建的方法了

 @RequestMapping(value = "/getJsonTest2",produces = "application/json")
    public String getUserTestMapper(@RequestBody String jsonString){
        String result = userTestMapper.getJsonReturnHello(jsonString);
        return result;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容