Spring Boot + Mybatis + Mysql配置

IDEA中創建Spring Boot項目(我用的是Gradle)配置mysql,先添加依賴,在build.gradle中添加mysql的依賴runtimeOnly 'mysql:mysql-connector-java'接着在application.properties中的配置如下:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSl=false
spring.datasource.username=root
spring.datasource.password=12345

其中:

  • spring.datasource.driver-class-name是mysql的驅動,spring.datasource.driver-class-name是mysql 5.7的驅動,8.0 的與這個不同。
  • spring.datasource.url表示連接哪個機器上的mysql、通過哪個端口連接以及連接mysql中的哪個數據庫。
  • spring.datasource.username:mysql用戶名。
  • spring.datasource.password:mysql密碼。

完成上述配置就能實現應用程序在mysql中讀寫數據。

Mybatis的配置也很簡單,在application.properties如下:

mybatis.config-location=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*.xml

mybatis.config-location指定的Mybatis配置文件文件的所在路徑。classpath:mybatis-config.xml表示是Mybatis的配置在Spring Boot項目中的resources 路徑下的mybatis-config.xml文件中。mybatis.mapper-locations指定的了mybatis的mapper文件所在的目錄。

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
	PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
		<setting name="cacheEnabled" value="true"/>
		<!-- Sets the numfindByNamer of seconds the driver will wait for a response from the database -->
		<setting name="defaultStatementTimeout" value="3000"/>
		<!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
		<setting name="mapUnderscoreToCamelCase" value="true"/>
		<!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
		<!-- Allows JDBC support for generated keys. A compatible driver is required.
		This setting forces generated keys to be used if set to true,
		 as some drivers deny compatibility but still work -->
		<setting name="useGeneratedKeys" value="true"/>
	</settings>

	<typeHandlers>
		
	</typeHandlers>


	<!-- Continue going here -->

</configuration>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章