SpringBoot整合mybatis入门
创建一个Spring Initializr 项目,Project SDK 1.8
Web 加入Spring Web,SQL加入MyBatis Framework
pom.xml引入相关依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
创建如下结构:
修改application.properties 为application.yml 写如下相关配置:
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&useSSL=false username: root password: 123456 mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.example.mybaits.entity configuration: map-underscore-to-camel-case: true
编写实体类:
public class User { private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
编写接口mapper
@Mapper//这是一个操作数据库的mapper public interface UserMapper { public List<User> allUser(); }
编写在resources文件中创建 mapper/UserMapper.xml文件
注意:
1.namespace中需要与使用@Mapper的接口对应
2.UserMapper.xml文件名称必须与使用@Mapper的接口一致
3.标签中的id必须与@Mapper的接口中的方法名一致,且参数一致
2.UserMapper.xml文件名称必须与使用@Mapper的接口一致
3.标签中的id必须与@Mapper的接口中的方法名一致,且参数一致
<?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.mybaits.mapper.UserMapper"> <select id="allUser" resultType="User"> SELECT * FROM tbuser </select> </mapper>
编写service接口
public interface UserService { public List<User> allUser(); }
Service接口的具体实现:
@Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> allUser() { return userMapper.allUser(); } }
userMapper这里可能会提示有误,不用管也没关系,不过你看着那红线实在难受,就将@Autowired 改为 @Resource 即可
最后编写Controller访问地址类
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/test")
public List<User> allUser(){
return userService.allUser();
}
}
创建个test数据库,在创建个tbuser表
运行后访问:
理一下思路,首先是创建 实体类User对象。然后创建UserMapper数据库操作接口,它的实现由mybatis来完成。然后创建UserService,以及实现接口类UserServiceImpl,来获取数据的返回结果。最后通过UserController类将结果输出到前台。
项目代码:
https://github.com/testwc/SpringMybatisTest