1、创建Springboot项目
2、创建所需的包(controller、dao、po、service、util)
3、在pom.xml
文件中添加相关依赖(可以去maven仓库搜索其他版本)
<!-- mybatis-spring-boot -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
4、在application.yml
(或者application.properties
)中写入数据库相关配置
- yml:
server: port: 8080 spring: datasource: username: root password: aaaaaa driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/test01?serverTimezone=UTC
- properties:
server.port=8080 spring.datasource.username=root spring.datasource.password=aaaaaa spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test01?serverTimezone=UTC
5、创建测试数据库表并随便写入数据(数据库名为test01
)
6、在PO
包中创建对应的实体类StudentPo
import org.springframework.stereotype.Component;
@Component
public class StudentPo {
private int id;
private String name;
private Integer age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public StudentPo(String name, Integer age) {
this.name = name;
this.age = age;
}
public StudentPo() {
}
@Override
public String toString() {
return "StudentPo{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
7、在DAO层创建mapper接口StudentDao
操作数据库
import com.wave.test.po.StudentPo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface StudentDao {
// 获取所有学生信息
@Select("select * from student")
List<StudentPo> getAll();
}
8、在Service层创建业务层处理mapper接口StudentService
返回的数据(这里省略业务层接口)
import com.wave.test.dao.StudentDao;
import com.wave.test.po.StudentPo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentService {
@Autowired
StudentDao dao;
/**
* 获取所有学生信息
* @return
*/
public List<StudentPo> getAll() {
return dao.getAll();
}
}
9、在控制层中创建StudentController
进行测试
import com.wave.test.po.StudentPo;
import com.wave.test.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
StudentService service;
/**
* 获取所有学生信息
* @return
*/
@GetMapping("/getAll")
public List<StudentPo> getAll() {
return service.getAll();
}
}
10、访问http://localhost:8080/student/getAll,结果如下为成功
后续文章: