1. 创建Spring Boot项目: 创建一个Spring Boot项目,可以使用Spring Initializer或手动创建

2. 添加依赖: 在pom.xml文件中,添加Spring Boot、MyBatis和数据库驱动程序的依赖,就像之前所示。
-
-
org.springframework.boot -
spring-boot-starter-web -
-
-
org.mybatis.spring.boot -
mybatis-spring-boot-starter -
2.3.1 -
-
-
-
org.springframework.boot -
spring-boot-starter-test -
test -
-
-
org.mybatis.spring.boot -
mybatis-spring-boot-starter-test -
2.3.1 -
test -
-
-
mysql -
mysql-connector-java -
-
3. 配置数据源: 在application.properties或application.yml文件中配置数据库连接信息。例如:
- spring:
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useSSL=true
- username: root
- password: 123456
4. 创建实体类: 创建实体类和数据库表之间的映射,可以使用@Entity注解,也可以使用@Table、@Id等MyBatis或JPA的注解。
- package com.example.demo.entity;
-
- import lombok.Data;
-
- @Data
- public class Sample {
- private Long id;
- private String name;
- private String sex;
- private int age;
-
- }
5. 创建Mapper接口: 创建一个MyBatis的Mapper接口,并使用@Mapper注解进行标记。
- package com.example.demo.mapper;
-
- import com.example.demo.entity.Sample;
- import org.apache.ibatis.annotations.Mapper;
-
- import java.util.List;
-
- @Mapper
- public interface SampleMapper {
- List
findAll(); - }
6.创建Service层: 创建Service层,处理业务逻辑,并将Mapper接口注入Service中。
- public interface SampleService {
- public List
findAll(); -
- }
- import java.util.List;
- @Service
- public class SampleServiceImpl implements SampleService{
- @Autowired
- SampleMapper sampleMapper;
- @Override
- public List
findAll() { - return sampleMapper.findAll();
- }
- }
7. 创建Controller: 创建一个Controller层,处理HTTP请求,调用Service层的方法。
这里注意要使用RestController注解不能用Controller不然前端调用会报404
- @RequestMapping("sample")
- @RestController
- public class SampleController {
- @Resource
- SampleService sampleService;
- @GetMapping("find-all")
- public List
list(){ - List
all = sampleService.findAll(); - return all;
- }
- }
8. 配置Mapper扫描路径: 使用@MapperScan注解来指定MyBatis的Mapper接口扫描路径,通常在Spring Boot应用的启动类上使用。
- @SpringBootApplication
- @MapperScan("com.example.demo.mapper")
- public class DemoApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(DemoApplication.class, args);
- }
-
- }