在dao包下创建UserDao.java
public interface UserDao { //插入用户 int insert(User user); //根据id查询 User selectById(String id); //查询所有 List<User> selectAll(); } 在mapper文件夹下创建UserMapper.xml,具体的xml编写方法查看文首的官方文档。
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.example.mybatistest.dao.UserDao"> <sql> user </sql> <sql> id,name,age,password </sql> <insert parameterType="com.example.mybatistest.entity.User" useGeneratedKeys="true" keyProperty="id"> INSERT INTO <include refid="BASE_TABLE"/> <trim prefix="(" suffix=")" suffixOverrides=","> name,password, <if test="age!=null"> age </if> </trim> <trim prefix=" VALUE(" suffix=")" suffixOverrides=","> #{name,jdbcType=VARCHAR},#{password}, <if test="age!=null"> #{age} </if> </trim> </insert> <select resultType="com.example.mybatistest.entity.User"> select <include refid="BASE_COLUMN"/> from <include refid="BASE_TABLE"/> where id=#{id} </select> <select resultType="com.example.mybatistest.entity.User"> select <include refid="BASE_COLUMN"/> from <include refid="BASE_TABLE"/> </select> </mapper> 至此使用mybatis的代码编写完了,之后要用时调用dao接口中的方法即可。
3.测试 我们通过编写service,controller然后使用postman进行测试。
首先编写UserService.java,代码如下:
@Component public class UserService { @Autowired private UserDao userDao; public User getByUserId(String id){ return userDao.selectById(id); } //获取全部用户 public List<User> getAll(){ return userDao.selectAll(); } //测试分页 public PageInfo<User> getAll(int pageNum,int pageSize){ PageHelper.startPage(pageNum,pageSize); List<User> users = userDao.selectAll(); System.out.println(users.size()); PageInfo<User> result = new PageInfo<>(users); return result; } public int insert(User user){ return userDao.insert(user); } } 编写UserController.java
@RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user/{userId}") public User getUser(@PathVariable String userId){ return userService.getByUserId(userId); } @GetMapping("/user") public List<User> getAll(){ return userService.getAll(); } @GetMapping("/user/page/{pageNum}") public Object getPage(@PathVariable int pageNum, @RequestParam(name = "pageSize",required = false,defaultValue = "10") int pageSize){ return userService.getAll(pageNum,pageSize); } @PostMapping("/user") public Object addOne(User user){ userService.insert(user); return user; } } 启动项目,通过postman进行请求测试,测试结果如下:
插入数据:
查询数据