简体   繁体   中英

How do we connect MySql database in SpringBoot?

I am beginner for Spring Boot and I want to connect to a MySQL database(8.0.15) but when I run my application I am getting the below exception and I am not able to understand it. How can I resolve this problem?

java.sql.SQLException: The connection property 'zeroDateTimeBehavior' only accepts values of the form: 'exception', 'round' or 'convertToNull'. The value 'CONVERT_TO_NULL' is not in this set.

application.properties

spring.datasource.url= jdbc:mysql://localhost:3306/sakila?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=root

将连接字符串更改为zeroDateTimeBehavior=convertToNull而不是zeroDateTimeBehavior=CONVERT_TO_NULL

Step 1 - Add dependency for your database connector to pom.xml Example for MySQL is shown below.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

If you would want to connect to oracle database, you can use a dependency similar to the one shown below.

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.1</version>
</dependency>

Step 2 - Remove H2 Dependency from pom.xml Or at least make its scope as test

<!--
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>
-->

Step 3 - Setup your My SQL Database We would need to set up your database with a schema and the tables.

For an example, check out - https://github.com/in28minutes/jpa-with-hibernate#installing-and-setting-up-mysql

Step 4 - Configure your connection to Your Database Configure application.properties to connect to your database.

An example for My SQL is shown below:

spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/todo_example
spring.datasource.username=todouser
spring.datasource.password=YOUR_PASSWORD

spring.jpa.hibernate.ddl-auto

Spring Boot chooses a default value for this based on whether you are connecting to an embedded database or not.

Embedded Databases - default create-drop
Other Databases - default none

Here is a quick guide to all the options

none : No action will be performed.
create-only : Database creation will be generated from entities.
drop : Database dropping will be generated from entities.
create : Database dropping will be generated followed by database creation.
validate : Validate entites with the database schema
update: Update the database schema based on the entities

Step 5 - Restart and You are ready! That's it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM