本篇文章描述使用SpringBoot整合Mybatis,以查询User为例。
1、在pom.xml中引入MySQLDriver和Mybatis的依赖(新建项目时已选择MySQLDriver和Mybatis,创建项目后已添加在pom中),若没有,可手动添加,添加后,需点击右侧的MAVEN,点击左上角的Reload按钮重新下载依赖。
<!-- mybatis启动依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- mysql依赖-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
<scope>runtime</scope>
</dependency>
2、使用数据库连接工具(例如navicat)或命令行 ,新建数据库和表。新建user表,字段有id、name、birdth。
3、编写配置文件(application.yml或者application.properties),连接数据库,此处以application.yml为例
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:端口号/数据库名称
username: 你的数据库用户名称,一般为root
password: 你的数据库密码
4、新建实体类,与user表对应
注意:使用@Data注解,需要引入Lombok依赖,可在新建项目时选择Lombok引入,也可以手动安装Lombok插件引入,引入后需重启IDEA。
package com.example.demo.dao;
import lombok.Data;
//@Data注解在类上面使用,可自动为变量生成getter和setter方法,简化代码。
@Data
public class User {
private int id;
private String name;
private String birdth;
}
5、编写controller类,向外暴露查询user的接口
请求路径为:/findById,可通过传入id查询对应id的数据
package com.example.demo.controller;
import com.example.demo.dao.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findById")
public User findById(Integer id) {
return userService.findById(id);
}
}
6、编写service接口,供controll调用
package com.example.demo.service;
import com.example.demo.dao.User;
public interface UserService {
public User findById(Integer id);
}
7、编写service接口的实现类,具体的实现逻辑写在这里。
在实现类里调用mapper层中的查询接口,查询等于传入id对应的user数据
package com.example.demo.service.impl;
import com.example.demo.dao.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findById(Integer id) {
return userMapper.findById(id);
}
}
8、编写Mapper层,实现与数据库的交互。
提供一个接口,这个接口可根据id查询user表的数据。
package com.example.demo.mapper;
import com.example.demo.dao.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
public User findById (Integer id);
}
9、运行项目,在浏览器请求接口,成功查询到id=1的user数据