第一步:首先引入依赖
//mysql依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
//mybatis依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>
//德鲁伊druid数据源依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
第二步:连接数据库
我这里使用的是安装在Linux中的Mysql,与在Windows上的操作是一样的
第三步:配置application.yml文件
spring:
datasource:
//配置mysql
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.136.132/mydb
username: root
password: 1234
//配置Druid数据源
type: com.alibaba.druid.pool.DruidDataSource
第四步:开始编码实现
这里我便于快速开发,只写了Controller层和Mapper层,Service层一般用于数据处理,暂时先不写,实体类的话这里也不做展示,很简单
Controller层:
package com.example.springboot_learn.Controller;
import com.example.springboot_learn.ApplicationData;
import com.example.springboot_learn.JsonResult;
import com.example.springboot_learn.Pojo.Book;
import com.example.springboot_learn.Pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.springboot_learn.mapper.studentmapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class BookController {
//依赖注入Mapper层接口
@Autowired
private studentmapper sm;
//设置API,并且从Mapper层获取数据返回给前端
@GetMapping("/selectstudent")
public JsonResult SelectStudent(){
List<Student> sdlist=sm.list();
System.out.println(sdlist);
return new JsonResult(sdlist);
}
}
Mapper层:
package com.example.springboot_learn.mapper;
import com.example.springboot_learn.Pojo.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
//Mapper注解将其放到Spring容器中
@Mapper
public interface studentmapper {
//select注解进行查询数据,此外还有delete,insert,update都是一样的用法
@Select("select * from mydb.student")
List<Student> list();
}
启动项目,根据API成功获取到从数据库查询到的数据