简体   繁体   中英

Make schema created by Spring JDBC the default schema

I'm using Spring Boot and JDBC for my database connection. I placed schema.sql at the classpath to initialize a schema and tables.

Because the schema doesn't exist yet while connecting to the datasource, I have to configure the datasource in application.properties like so:

spring.datasource.url=jdbc:mysql://localhost:3306/

schema.sql:

CREATE DATABASE IF NOT EXISTS <schema_name>
USE <schema.name>;

CREATE TABLE...

So I select the schema after creating it. This obviously doesn't persist for too long.

How do I configure this properly? Is there a way to select a default schema after the create script or maybe change the datasource url?

With JDBC you need to use Connection.setCatalog to switch between databases. You should not use USE <databasename> as the JDBC driver itself needs to be aware of which database it is operating on.

Based on your code from the schema.sql

USE <schema.name>;

This will not work for your java environment. The schema.sql will be executed and finished, which will not cater your requirement to set the default schema. The General approach will be to use JDBC URL as;

jdbc:mysql://localhost:3306/DB_NAME

This will set the default db as DB_NAME. Assumptions: I am assuming that you want to connect to single node DB without any loadbalancer or failover mechanism to be used. URL may change based on these features to be configured.

If you are not specifying the DB_NAME in the URL, it means their is no default schema. You have 2 options to access the DB in that case.

1) Always use the Connection.setCatalog() method to specify the desired database in JDBC applications, rather than the USE database statement.

2) fully specify table names using the database name (that is, SELECT dbname.tablename.colname FROM dbname.tablename ...) in your SQL. Opening a connection without specifying the database to use is generally only useful when building tools that work with multiple databases, such as GUI database managers.

For more details refer to the below mysql portal for reference.

https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html

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