前言
我們上一次 通過SpringBoot 搭建完WebServer了
SpringBoot創建 WebServer項目
那麼我們一般api都會涉及到數據庫的操作。
那麼如何來實現jdbc的鏈接呢?
還記得我們創建項目時,選擇的
JDBC API //這是是java 的JDBC 封裝庫,
MySQL Driver //這個是JDBC訪問數據庫時需要對應數據庫的驅動。我們也加載了
MyBatis Framework // 這個MyBatis這個就是用來解決SQL 語言的注入等操作的。 讓我們擺脫了每一個數據庫查詢都需要重寫一遍SQL語言並調用的步驟
下面我們來使用它,自動生成SQL語言。
1.添加自動插件 Free MyBatis plugin。
我們需要主動添加Plugin插件。沒有這個插件我們也可以自己寫,但是很繁瑣。這個插件可以自動幫我們生成。
2.pom.xml 文件之中配置plugins腳本
上一步只是添加了plugins 到IDEA之中,我們這一步需要將該plugins 加載到我們的Project的編譯之中,讓我們在當前項目中可以利用該Plugins。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!--這是我們要添加的代碼 mybatis generator 自動生成代碼插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<!--配置文件的位置-->
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
然後在configurationFile 標籤標註的地方,創建generatorConfig.xml 文檔。
創建完畢後效果如圖所示:
3.編輯generatorConfig.xml 腳本。
該腳本利用了MyBatis的語法規則,進行自動創建mapper.xml 文檔。而關於MyBatis 的語法有想深入瞭解,可以通過官網進行了解:https://mybatis.org/mybatis-3/zh/index.html
同時附上鍊接 Github
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> //
<generatorConfiguration>
<!-- 數據庫驅動:選擇你的本地硬盤上面的數據庫驅動包-->
<classPathEntry location="C:\Users\xx\.m2\repository\mysql\mysql-connector-java\8.0.19\mysql-connector-java-8.0.19.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自動生成的註釋 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--數據庫鏈接URL,用戶名、密碼 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://172.0.0.0:3306/test?serverTimezone=GMT%2B8" userId="用戶名"
password="密碼">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.demo.entity 這個就是你的實體Bean 對象的存儲路徑" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<!-- 設置是否在getter方法中,對String類型字段調用trim()方法-->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="main.resources.mappers" targetProject="src">
<!-- enableSubPackages:是否讓schema作爲包的後綴 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.demo.dao 這個路徑可以自己決定存儲。"
targetProject="src/main/java">
<property name="mapper" value="true"/>
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名 就是你想生成的Bena對象的類名-->
<table tableName="login_info"
domainObjectName="LoginInfo"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
<table tableName="userinfo"
domainObjectName="UserInfo"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
在下面 會針對相關配置屬性我做一個介紹。可以往下看
如果不知道MySQL 驅動的路徑怎麼辦?
4.執行腳本
配置完GeneratorConfig 之後,我們需要主動去執行該腳本,來自動生成相關SQL代碼和bean對象
mybatis-generator:generate -e
完成之後, 這裏就會添加一個maven的執行程序,選擇這個,點擊右側的運行按鈕,就可以了。
5.執行編譯,得到結果。
正常結果
出現BUILD SUCCESS 就代表執行成功了。
代碼結構文件如圖所示; 全部根據配置文件自動生成
及bean實體對象。
之後就是調用相關方法實現數據庫讀寫了。
錯誤情況
Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate (default-cli) on project demo: Unknown database 'xxx'
如果出現上面的錯誤,代表了在generatorConfig之中輸入的數據庫名稱錯誤,請檢查你的數據庫是否正確
6.編輯相關API接口
創建Server
@Service
public class LoginServer {
@Autowired
LoginInfoMapper loginInfoMapper;
public void install(LoginInfo loginInfo){
loginInfoMapper.insert(loginInfo);
}
}
創建Controller
@RestController
@RequestMapping("/api")
public class APIController {
@Autowired
LoginServer loginServer;//登錄服務器操作
/**
* post 請求
*
* @return
*/
@RequestMapping(value = "login", method = RequestMethod.POST)
public LoginInfo addLogin(@RequestParam String devicesId) {
LoginInfo deviceInfo = new LoginInfo();
deviceInfo.setDevicesId(devicesId);
deviceInfo.setNum(1);
deviceInfo.setAddtime(new Date(System.currentTimeMillis()));
loginServer.install(deviceInfo);
return deviceInfo;
}
}
錯誤情況:
1.
Consider defining a bean of type 'com.example.demp.server.LoginServer' in your configuration.
添加方式:
在application.yml文件之中添加下面代碼
mybatis:
mapper-locations: classpath:mappers/*.xml
type-aliases-package: com.example.demp.dao
2.
運行之後如果還出現下面錯誤
Description:
Field loginServer in com.example.demo.controller.APIController required a bean of type 'com.example.demo.server.LoginServer' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.demo.server.LoginServer' in your configuration.
這是因爲註解信息丟失造成的問題。
@Mapper
public interface LoginInfoMapper {
在生成的dao 路徑下的Mapper類,添加上@Mapper 註解標籤。
如果添加@Mapper 標籤之後 還是報該錯誤,那是因爲你的dao對象目錄 沒有在DempApplication 類的目錄結構下。
main 方法會遍歷同一級目錄下的。如果不是在同一級目錄下,你就需要主動添加掃描的目錄
@ComponentScan({"com.demp.service.dao 你需要手動開啓掃描的目錄"})
7.完成api調用
到這裏,我們就完成了api的開發,以及請求數據存儲到MySQL的完整流程了。
而如果對於sql語法想進行修改,或者自動生成的不滿足需求。可以手動在mappers.xml文件之中添加,然後在java 文件之中填寫接口地址,就可以了。 更具體的可以參考MyBatis文檔之中的各種標籤說明。
想了解GeneratorConfig 的所有參數的配置意義,可以參考我的下一篇博客: GeneratorConfig 屬性配置大全