Spring Boot整合mybatis
主页有Spring Boot的入门案列 希望大家多瞅一瞅
现在让我们来整合spring boot和mybatis吧
第一步:准备工作
- 打开idea 创建一个spring boot新项目
- 创建项目的时候把下面依赖导入
- mysql依赖:
-
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
- JDBC依赖:
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
- web依赖:
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
- mybatis依赖:
-
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency>
第二步:
- 配置文件中写入数据库信息
spring.datasource.username=root spring.datasource.password=5825600 spring.datasource.url= jdbc:mysql://localhost:3306/luyunjie?useSSL=false&useUnicode=false&characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#你的User类在那里就写那里的路径 mybatis.type-aliases-package=com.kuang.bojo #你的.xml配置文件在那里就写你配置文件的路径
mybatis.mapper-locations=classpath:com/kuang/ban/*.xml
第三步创建类和接口:
- User类:
@Data @AllArgsConstructor @NoArgsConstructor public class User { private Integer id; private String name; private Integer tid; }
接口:
//表示是mybatis的注解类 @Mapper @Component public interface UserMapper { //查找全部元素方法 List<User> queryList(); }
第四步:写出mybatis的配置文件:UserMapper.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.kuang.ban.UserMapper"> <select id="queryList" resultType="User"> select * from student; </select> <select id="querygetId" resultType="User" parameterType="int"> select * from student where id = #{id}; </select> </mapper>
第五步:写出UserController测试类直接测试:
@RestController public class UserController { @Autowired private UserMapper userMapper; @RequestMapping("/r") public List<User> queryUserList(){ List<User> users = userMapper.queryList(); for (User user : users) { System.out.println(user); } return users; } }
最后一步:点击测试然后打开浏览器输入:http://localhost:8080/r 即可测试;