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>