~~ 在此之前,寫過關于SpringBoot的IDEA快速部署,不會步驟的大家可以去看一哈,有問題的就留言,淺談之SpringBoot的環境搭建及快速入門 QuQ
Spring整合Mybatis
- 添加Mybatis的起步依賴
- 添加資料庫的驅動坐標
- 創建user表
- 創建物體Bean
- 撰寫Mapper
- 配置Mapper組態檔
- 在application.properties中添加mybatis的資訊
- 測驗:Controller
pom.xml:
<!-- mybatis起步依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!--MySQL連接驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
資料庫連接資訊:application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
如果你的專案配置爆紅了: 顯示Cannot resolve class or package 'mysql'

- 別著急,因為我在匯入Oracle的時候也遇到了同樣的問題,就是:Oracle和Mysql的jar包依賴默認是runtime,相當于代碼中的:
<scope>runtime</scope>,也就是說只有運行的時候才會生效,所以你寫代碼的時候當然找不到這個包, - 最簡單的方法就是改為(非SpringBoot專案):
compile<scope>compile</scope> - 你也可以去idea中徹底改了(自己百度),不推薦,idea那樣設定是有原因滴!
- 此外就是idea最新版,SpringBoot專案已經解決了這個問題,最好還是使用默認的runtime
注:關于資料庫連接問題(application.properties)
- 以前使用:com.mysql.jdbc.Driver
- 我的版本使用:com.mysql.cj.jdbc.Driver

創建并錄入資料:

user物體類:(并且生成他的get、set以及toString方法,我就不掛出來了)
private Integer id;
private String username;
private String password;
private String name;
物體類的映射:resources下新建一個Mapper檔案夾(UserMapper.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.fan.mapper.UserMapper">
<select id="queryUserList" resultType="user">
select * from user
</select>
</mapper>
SpringBoot中配置Mybatis資訊(application.properties):
#spring集成mybatis環境
#pojo別名掃描包
mybatis.type-aliases-package=com.fan.domain
#加載MyBatis映射檔案
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
測驗:Controller
@Controller
public class MybatisController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/query")
@ResponseBody
public List<User> queryUserList(){
List<User> users=userMapper.queryUserList();
return users;
}
}
測驗結果:SpringBoot成功整合mybatis

注:此外還是一個關于資料庫連接的問題:
報錯資訊:Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: The server time zone value '�й���??��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specific time zone value if you want to utilize time zone support.
- 資料庫是好的,連接資訊沒有錯啊,為什么會報這樣的錯誤呢?
于是去百度,得到了這樣的解釋:使用mysql的jdbc驅動最新版(6.0+)時,會遇到資料庫和系統時區差異引起的問題,(注:CST代表的是中國上海時間(與北京時間,東八區相同)), - 怎么解決呢?
在 jdbc的url后拼接serverTimezone=CST
spring.datasource.url=jdbc:mysql://localhost:3306/spring?&serverTimezone=UTC&....
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/204685.html
標籤:其他
