一、Spring Boot连接MySQL数据库
使用mybatis连接MySQL数据库,在prm.xml中添加配置依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
在application.properties中添加数据库配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=用户名
spring.datasource.password=密码
spring.datasource.url=jdbc:mysql://localhost:3306/库名?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
二、编写MySQL表对应的实体类
package com.jackie.adminjava;
public class Student {
Integer id;
String name;
public void setId(Integer id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getId() { return id; }
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + ''' +
'}';
}
}
三、编写实体类对应的Mapper
package com.jackie.adminjava;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import org.apache.ibatis.annotations.Mapper;
@Mapper
@Repository
public interface StudentMapper {
@Select("select * from students where id = #{id}")
Student findById(Integer id);
}
四、编写实体类对应的Service
package com.jackie.adminjava;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
@Autowired
StudentMapper studentMapper;
public Student findStudent(Integer id) {
return studentMapper.findById(id);
}
}
五、编写实体类对应的Controller
package com.jackie.adminjava;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StudentController {
@Autowired
StudentService studentService;
@GetMapping("/student")
public String student(@RequestParam Integer num) {
Student student = studentService.findStudent(num);
return student.toString();
}
}
启动项目后在请求接口 /student?num=1 就可以请求到数据。
总结
- 依赖配置不可缺少,注意版本之间的差异。
- 实体类是对数据库的一种映射关系,负责对数据库数据进行组装。
- Mapper是对数据库数据进行查询。
- Service是对请求参数和其他业务逻辑进行处理。
- Controller接口定义,接收请求参数。