來源:素文宅博客
轉自:https://blog.yoodb.com/yoodb/article/detail/1565
Spring Boot可以大大簡化持久化任務,幾乎不需要寫SQL語句,本篇講述一下Spring Boot連接MySQL數據庫。
在之前章節“Spring Boot從入門到精通(一)搭建第一個Spring Boot程序”中我們新建了一個Spring Boot應用程序,本章在原有的工程中與MySQL數據庫建立連接。
Spring Boot有多種方式與數據庫建立連接,包括:使用JdbcTemplate;集成Mybatis等等。下面小編主要是爲大家介紹一下如何使用JdbcTemplate和集成Mybatis這兩種方式連接數據庫。
使用JdbcTemplate
在pom.xml文件增加如下包的引入,信息如下所示:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
maven項目編譯
maven編譯項目時報錯,信息如下:
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0,
Time elapsed: 4.216 s <<< FAILURE! - in
com.yoodb.study.demo02.SpringbootStudyDemo02ApplicationTests
contextLoads Time elapsed: 0.002 s <<< ERROR!
解決方式1:在pom.xml文件增加如下配置信息:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
解決方式2:使用命令參數,如下所示:
mvn install -Dmaven.test.skip=true
IntelliJ IDEA中運行maven安裝jar包到本地倉庫跳過test,如圖所示:
IntelliJ IDEA中新增Maven自定義命令,各個參數含義說明如下:
Name:自定義名稱;
Working directory:輸入路徑;
Command line:命令模式;
Profiles (separated with space):輸入相關信息
參考如圖所示:
在resource文件夾下application.properties配置文件中增加數據庫參數,信息內容如下:
spring.datasource.url=jdbc:mysql://123.57.47.154:3306/dba
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
在com.yoodb.study.demo02包下,新建Controller類測試數據庫連接,代碼如下:
package com.yoodb.study.demo02;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/jte")
public class JdbcTemplateController {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/getUsers")
public List<Map<String, Object>> getDbType(){
String sql = "select * from boot_user";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
for (Map<String, Object> map : list) {
Set<Entry<String, Object>> entries = map.entrySet( );
if(entries != null) {
Iterator<Entry<String, Object>> iterator = entries.iterator( );
while(iterator.hasNext( )) {
Entry<String, Object> entry =(Entry<String, Object>) iterator.next( );
Object key = entry.getKey( );
Object value = entry.getValue();
System.out.println(key+":"+value);
}
}
}
return list;
}
}
啓動Maven項目,輸入地址:
http://localhost:8080/jte/getUsers
通過瀏覽器訪問後,返回參數如下:
[{"id":1,
"user_name":"admin",
"password":"e10adc3949ba59abbe56e057f20f883e",
"role_name":"素文宅博客",
"detail":"歡迎關注“Java精選”微信公衆號,專注程序員推送
一些Java開發知識, 包括基礎知識、各大流行框架(Mybatis、
Spring、Spring Boot等)、大數據技術、(Storm、Hadoop、
MapReduce、Spark等)、數據庫(Mysql、Oracle、NoSQL等
算法與數據結構、面試專題、面試技巧經驗、職業規劃以及優質
開源項目等。其中一部分由小編總結整理,另一部分來源於網絡
上優質資源,希望對大家的學習和工作有所幫助。"}]
集成Mybatis
添加mybatis依賴,在pom.xml文件中增加如下:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
在resource文件夾下application.properties配置文件中增加數據庫參數,信息內容如下:
spring.datasource.url=jdbc:mysql://123.57.47.154:3306/dba
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
依次添加mapper的接口類和xml文件
BootUserMapper.java
package com.yoodb.study.demo02.mapper;
import com.yoodb.study.demo02.bean.BootUser;
import org.mybatis.spring.annotation.MapperScan;
import java.util.List;
public interface BootUserMapper {
List<BootUser> selectAll();
}
BootUserMapper.xml
<?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.yoodb.study.demo02.mapper.BootUserMapper" >
<resultMap id="BaseResultMap" type="com.yoodb.study.demo02.bean.BootUser" >
<id column="id" property="id" jdbcType="VARCHAR" />
<result column="user_name" property="name" jdbcType="VARCHAR" />
<result column="detail" property="detail" jdbcType="VARCHAR" />
</resultMap>
<select id="selectAll" resultMap="BaseResultMap">
select
id, user_name, detail
from boot_user order by detail asc
</select>
</mapper>
BootUser.java
package com.yoodb.study.demo02.bean;
import java.util.Date;
public class BootUser {
private String id;
private String name;
private String detail;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
}
BootUserService.java
package com.yoodb.study.demo02.service;
import java.util.ArrayList;
import java.util.List;
import com.yoodb.study.demo02.bean.BootUser;
import com.yoodb.study.demo02.mapper.BootUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BootUserService {
@Autowired
private BootUserMapper mapper;
public List<BootUser> getUsers(){
return mapper.selectAll();
}
}
BootUserController.java
package com.yoodb.study.demo02;
import java.util.List;
import com.yoodb.study.demo02.bean.BootUser;
import com.yoodb.study.demo02.service.BootUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/myt")
public class BootUserController {
@Autowired
private BootUserService service;
@RequestMapping("/getUsers")
public List<BootUser> getUsers() {
List<BootUser> list = service.getUsers();
return list;
}
}
代碼添加到項目中之後,啓動Maven項目,通過瀏覽器訪問,地址如下:
http://localhost:8080/myt/getUsers
訪問後控制檯提示錯誤信息如下:
org.apache.ibatis.binding.BindingException:
Invalid bound statement (not found):
com.yoodb.study.demo02.mapper.BootUserMapper.selectAll
問題分析:在mapper配置文件與接口做映射綁定時出現問題,它所指的就是接口與響應的xml找不到或者是匹配不到。
解決方式就是在pom.xml文件中增加如下配置信息:
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
重新啓動Maven項目,輸入地址:
http://localhost:8080/myt/getUsers
通過瀏覽器訪問後,返回參數如下:
[{"id":1,
"user_name":"admin",
"password":"e10adc3949ba59abbe56e057f20f883e",
"role_name":"素文宅博客",
"detail":"歡迎關注“Java精選”微信公衆號,專注程序員推送
一些Java開發知識, 包括基礎知識、各大流行框架(Mybatis、
Spring、Spring Boot等)、大數據技術、(Storm、Hadoop、
MapReduce、Spark等)、數據庫(Mysql、Oracle、NoSQL等
算法與數據結構、面試專題、面試技巧經驗、職業規劃以及優質
開源項目等。其中一部分由小編總結整理,另一部分來源於網絡
上優質資源,希望對大家的學習和工作有所幫助。"}]
至此,Spring Boot連接MySQL數據庫就說到這裏。如果需要項目源碼請大家切換至公衆號後臺輸入“Spring Boot從入門到精通”關鍵詞來獲取項目源碼。大家試一試吧,歡迎評論。