1、導入依賴
mybatis依賴:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
其它依賴:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
<scope>runtime</scope>
</dependency>
2、配置資料庫連接配接
spring:
datasource:
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/stu_mangement?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 預設是不注入這些屬性值的,需要自己綁定
#druid 資料源專有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置監控統計攔截的filters,stat:監控統計、log4j:日志記錄、wall:防禦sql注入
#如果允許時報錯 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#則導入 log4j 依賴即可,Maven 位址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3、建立一個實體類Student,使用了lombok需要導入相應的依賴
@Data
public class Student {
public Integer studentno;
public String birthday;
public String classno;
public String phone;
public String sex;
public String sname;
public Float point;
}
4、dao層
(1)建立dao層的接口
@Component
public interface StudentDao {
List<Student> getStudents();
}
(2)在resources目錄下建立配置檔案
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhb.dao.StudentDao">
<select id="getStudents" resultType="com.zhb.pojo.Student">
select * from student;
</select>
</mapper>
(3)注意
為了保證編譯後的接口和配置檔案在同一個目錄下,書寫接口與配置的時候需要注意目錄的建立方式:
編譯結果:
5、測試
書寫controller嘗試擷取資料:
@Controller
public class JDBCController {
@Autowired
StudentDao studentDao;
@RequestMapping("/query")
public String queryAll() {
System.out.println(studentDao.getStudents());
return "query";
}
}
測試結果:成功擷取到資料