今天来聊聊SpringBoot实例

Sprint Boot的完整实例,从数据库读取数据并使用Postman测试。

项目地址:https://github.com/Snowstorm0/learn-spring-boot

1 本地数据库

本地数据库创建教程:

创建本地数据库user_data:

2 代码主体

2.1 Controller

文件名MyController,内容为:

@RestController
@RequestMapping("/homepage")
public class MyController {
    @Resource
    MyService myService;
    @GetMapping("/learnSpringBoot")
    public String learnController(@RequestParam("number") int number){
        return myService.learnService(number);
    }
}

2.2 Service

文件名MyService,内容为:

@Service
@EnableScheduling
public class MyService {
    @Resource
    MyMapper myMapper;
    public String learnService(int number){
        UserDTO res = myMapper.LearnMapper(number);
        String name = res.getName();
        System.out.println("name:" + name + "\n");
        return name;
    }
}

2.3 dao

文件名MyMapper,内容为:

@Mapper
public interface MyMapper {
    UserDTO LearnMapper(int number);
}

2.4 model

文件名UserDTO,内容为:

@Data
public class UserDTO {
    private Integer number;
    private String name;
    public Integer getNumber() {
        return number;
    }
    public void setNumber(Integer number) {
        this.number = number;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

2.5 Application

在application.properties配置:

# 设置端口号
server.port=8888

在application.yml配置:

# 连接数据库
spring:
    datasource:
        url: jdbc:mysql://localhost:3306/sys
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: root
        username: root
# 配置mapper.xml路径
mybatis:  
    mapper-locations: classpath:mapper/*.xml  
    type-aliases-package: com.spring.root.dao

3 Postman

配置Get,地址为: http://localhost:8888/homepage/learnSpringBoot

输入number:1001

即可获得返回的name:赵一

正文完