目录
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-devtoolsartifactId>
- dependency>
添加后报红就刷新Maven。
2.在idea中设置自动编译
3.在Idea设置自动运行
但是complier.automake.allow.when.app.running这个选项在IntelliJ IDEA 2021.2之后的版本迁移到高级设置中,如下
此时热部署即可生效 。
- CREATE DATABASE student;
- USE student;
- DROP TABLE IF EXISTS student;
- CREATE TABLE student (
- id int(11) NOT NULL AUTO_INCREMENT,
- stuName varchar(255) DEFAULT NULL,
- sex varchar(10) DEFAULT NULL,
- stuAddress varchar(255) DEFAULT NULL,
- PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-
- insert into student(id,stuName,sex,stuAddress) values(1,'小明','男','北京'),(2,'尚尚','女','北京');
2.创建SpringBoot项目,添加MyBatis起步依赖和Mysql驱动依赖
除了SpringMVC(在Web模块)的依赖,还要添加Mybatis和MySQL驱动的依赖
测试依赖是默认自动引入的,不需要手动引入
以下步骤完了之后的项目结构:
3.编写实体类
- public class Student {
- private int id;
- private String stuName;
- private String sex;
- private String stuAddress;
-
- //省略get/set/toString方法
- }
4.编写Mapper接口
- import com.first.springbootmybatis.domian.Student;
- import org.apache.ibatis.annotations.Mapper;
-
- import java.util.List;
-
- @Mapper
- public interface StudentMapper {
- List
findAll(); - }
5.编写Mapper映射文件
要在resources下创建StudentMapper接口的映射文件,要和该接口在java文件下路径一致,且要一层一层的创建。即先创com,再创first,再创springbootmybatis
- "1.0" encoding="UTF-8"?>
- mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-
- <mapper namespace="com.first.springbootmybatis.mapper.StudentMapper">
-
- <select id="findAll" resultType="student">
- select * from student
- select>
- mapper>
6.编写配置文件
创建application.yml
- # 数据源
- spring:
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql:///student?serverTimezone=UTC
- username: root
- password: root
-
- # mybatis配置
- mybatis:
- # 映射文件位置
- mapper-locations: com/first/springbootmybatis/mapper/*Mapper.xml
- # 使别名domain下的文件都可以使用别名
- type-aliases-package: com.first.springbootmybatis.domain
- #日志格式
- logging:
- pattern:
- console: '%d{HH:mm:ss.SSS} %clr(%-5level) --- [%-15thread] %cyan(%-50logger{50}):%msg%n'
7.编写测试类
在test文件下创建,记得路径也要对应
- import com.first.springbootmybatis.domian.Student;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
-
- import java.util.List;
-
- // 测试类注解,可以在运行测试代码时加载Spring容 器
- @SpringBootTest
- public class StudentMapperTest {
- @Autowired
- private StudentMapper studentMapper;
- @Test
- public void testFindAll(){
- List
all = studentMapper.findAll(); - all.forEach(System.out::println);
- }
- }
运行测试类查看是否查询到了所有学生的信息。