SpringBoot 整合 MyBatis
本文基于:https://www.bilibili.com/video/BV15b4y1a7yG?p=28&vd_source=cf8900ba33d057d422c588abe5d5290d
在 pom.xml 中導入坐標
<dependencies>
...
<!-- 引入MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- 導入數據庫的jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
這里使用的數據庫是 MySql
配置 application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3309/FruitDatabase
username: root
password: 123456
上面的代碼夠語義化了,就不解釋了
新建實體類
延續之前的例子,建立一個 Fruit 類
package com.example.xxx.entity;
public class Fruit {
private String fruitId;
private String fruitName;
private String avatar;
private Double price;
private Integer stock;
// Getter&Setter
// toString
}
新建 Dao 接口

package com.example.xxx.dao;
import xxx...;
@Mapper
public interface FruitDao {
@Select("select * from fruit_table where fruit_id = #{id}")
public Fruit getById(String id);
}
去測試類中測試一下
// TestClass
package com.example.xxx;
import com.example.xxx.dao.FruitDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class TestClass {
@Autowired
private FruitDao fruitDao;
@Test
void contextLoads() {
System.out.println(fruitDao.getById("1"));
}
}
運行 contextLoads 方法:
xxx
Fruit{fruitId='null', fruitName='null', avatar='http://www.xxx.com/pears.jpg', price=74.2, stock=80}
xxx
成功讀取到了數據庫中的信息,不過這里的
fruitId和fruitName為null是由于我們配置實體類的字段名與數據庫中的字段名不匹配,數據庫中的字段是fruit_id這種形式,而 JAVA 實體類中使用的是 小駝峰,后續的博客應該會提到相關的內容 ??

浙公網安備 33010602011771號