How to connect Spring Boot Application with MySQL database? - mysql

I am new at spring framework, I want to connect my MySQL database which located in localhost with spring boot application.

I'm listing out the minimal configuration:
In pom.xml
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
In application.properties
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
You can get such examples everywhere. Prefer to read https://spring.io/guides/gs/accessing-data-mysql/
Source : https://spring.io
Checkout other questions too :
How to use Spring Boot with MySQL database and JPA?
Spring Boot MYSQL connection
Spring boot - MySQL settings are not working

You need to add database configuration properties for Mysql in your application.properties:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=mysql
spring.datasource.password=mysql
spring.jpa.hibernate.ddl-auto=create this configuration will create tables based on your entities which were created by you.
spring.datasource.url=jdbc:mysql://localhost:3306/db_example this configuration connects through jdbc to your database called db_example. You need to create that database.
spring.datasource.username=mysql this configuration you need to put your user who will connect via jdbc to your mysql database.
spring.datasource.password=mysql this configuration you need to provide your password which is represented by your user in order to connect through jdbc to your mysql database.
In addition tou you need to add dependencies for Mysql and JPA.
If you are using maven, add the dependencies in your pom.xml:
<dependencies>
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
If you are using gradle, add the dependencies in build.gradle:
dependencies {
// JPA Data (We are going to use Repositories, Entities, Hibernate, etc...)
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
// Use MySQL Connector-J
compile 'mysql:mysql-connector-java'
}

Add below dependencies in pom.xml.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
Add below database properties in application.properties.
spring.datasource.url=jdbc:mysql://localhost:3306/dbname
spring.datasource.username=root
spring.datasource.password=root
For more details please refer this link

To connect with mysql need some dependencies as below
Dependencies (maven -> pom.xml).
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
in application.properties need some extra configuration setting which must like like
application.properties (src/main/resources/application.properties)
# DataSource settings: set here your own configurations for the database
# connection. In this example we have "netgloo_blog" as database name and
# "root" as username and password.
spring.datasource.url = jdbc:mysql://localhost:8889/database_name
spring.datasource.username = mysql-userId
spring.datasource.password = mysql-pwd
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy (Not necessary to add but you can use this too)
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Now your EntityManager Object will be constructed when you starts your spring boot Configuration.
Above defined configuration is enough to connect your local my-sql database but here is some more configuration that you need to make your code more readable.
Enable JPARepositories such that CRUD Repositories must defined in a defined package.
Add #EnableJPARepositories("basepackage.*") to your SpringBootMainApplicationClass like this..
#SpringBootApplication
#EnableJPARepositories("com.demo.application.*.repositories")
#ComponentScan("com.demo.application.*")
public class SpringBootMainApplicationClass {
public static void main(String[] args) {
SpringApplication.run(SpringBootMainApplicationClass.class, args);
}
}
by adding #EnableJPARepositories Annotation in MainClass enables user to make your code more readable and EntityManager Object only restricted to only defined package.

application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/jpa
spring.datasource.username = root
spring.datasource.password =
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
build.gradle
implementation 'mysql:mysql-connector-java:8.0.15'

Related

H2 and mysqldriver error: jdbcUrl not accepted

I've created a spring boot application running in my dev-environment with H2 dependency. This was working fine. After also adding mysql driver in the dependencies, for testing in cloud purposes, I cannot use the H2 configuration anymore, because of the following error:
Driver com.mysql.cj.jdbc.Driver claims to not accept jdbcUrl, jdbc:h2:mem:memDb;DB_CLOSE_DELAY=-1
However, my application.properties that's being used, doesn't specificy to use the mysql driver. How to solve?
Application.properties:
# H2 DB settings
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:mem:memDb;DB_CLOSE_DELAY=-1
spring.datasource.driveClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Dependencies:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>

Connecting to mysql database as a data source in eclipse web app

I can connect to the embedded h2 database, but am confused about the correct syntax for connecting to a mysql database named 'test1'. For example, I would like to know what to substitute in the pom.xml, web.xml and persistence.xml files instead of the h2 terminology.
I'm using mysql 5.7.27, with mysql-connector-java-8.0.27.jar in my src/main/resources/META-INF/lib folder. My url is jdbc:mysql://localhost:3306/test1
pom.xml - what to use for groupId and artifactId
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2></artifactId>
<version>1.4.200</version>
</dependency>
web.xml - what to use for name and class
<data-source>
<name>java:global/DataSourceName>
<class-name>org.h2.jdbcx.JdbcDataSource</class-name>
<url>jdbc:h2:mem;DB_CLOSE_DELAY=-1</url>
</data-source>
persistence.xml - does this need to change
<persistence-unit name="PersistenceUnitName"
transaction-type="JTA">
<jta-data-source>java:global/DataSourceName</jta-data-source>
<properties>
<property
name="javax.persistence.schema-generation.database.action"
value="none" />
</properties>
</persistence.unit>
</persistence>
follow this Guide to configure all things you need to connect to MySQL or MariaDB.Use the bellow configuration for MySQL.
- in step (1) use The right classname of MySQl DataSource as bellow:
datasource-classname="com.mysql.cj.jdbc.MysqlDataSource"
Ref: MySQL Doc - Configuration Properties
- In step (3) Add this in POM.XML:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>x.y.z</version>
</dependency>
Ref: MySQL Doc - Installing MySQL Connector/J Using Maven

SpringDoc OpenAPI swagger MergeAnnotations error

I am trying to configure OpenAPI with swagger to my existing non-spring boot application.
Spring v.5.1.8.RELEASE
SpringDoc v.1.4.6
Spring-boot v.2.3.2.RELEASE
Open doc and swagger with spring mv
My application is not spring boot enable that’s why I have following dependencies in my Pom copied from article linked above
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>last.version</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>2.1.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.1.11.RELEASE</version>
</dependency>
My Spring mvc project already has servlet context configuration so I assumed I only need to register/import open api and swagger configuration files.
So I did the following
#EnableMvc
#Configuration
#import({org.springdoc.ui.SwaggerConfig.class,
org.springdoc.core.SwaggerUiConfigProperties.class, org.springdoc.core.SwaggerUiOAuthProperties.class,
org.springdoc.webmvc.core.SpringDocWebMvcConfiguration.class,
org.springdoc.webmvc.core.MultipleOpenApiSupportConfiguration.class,
org.springdoc.core.SpringDocConfiguration.class, org.springdoc.core.SpringDocConfigProperties.class,
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration.class
#Bean
Public OpenAPI(){
return new OpenAPI();
}
When I run my application I gets the following error
“Java.lang.NoSuchMethodError:org.springframework.core.type.AnnotatgedTypeMetadata.getAnnotations()/Lorg/springframework/core/annotations/MergeAnnotations”
It was caused due to incompatible version of spring mvc and spring-boot

on AWS - could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet aws

I have this (common) problem with my DB access. But in my case, I dont find the right answere...
Created a very basic MySql DB and Spring Boot App accessing it.
On my localhost it runs smooth.
Then I dumped the local DB. Inserted it into the AWS-MySql DB.
And deployed the Spring-Boot app with Docker to my EC2.
Everything is well.
But on using the AWS MySQL all REST Endpoints return:
status 500
could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
For me it looks like all the same as it was on localhost.
What did I miss?
I found the cause. I know a solution.
BUT I cant accept to not to know how it happend:
My POJOs are defined by Classname only (no Table="" Metadata decortion)
On my local machine it runs well.
The SQL query is: "... 'Dbname'.'tablename' ... "
Dockerized on AWS on the RDS Mysql.
The SQL query is: "... 'Dbname'.'TableName' ... "
And then the of course the query fails.
My configs:
properties:
#Hibernate (Spring-JPA)
hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
POM:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud-services.version>1.5.0.RELEASE</spring-cloud-services.version>
<spring-cloud.version>Dalston.SR3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>io.pivotal.spring.cloud</groupId>
<artifactId>spring-cloud-services-starter-service-registry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.pivotal.spring.cloud</groupId>
<artifactId>spring-cloud-services-dependencies</artifactId>
<version>${spring-cloud-services.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
So obviously my NamingStrategy settings will be ignored or overriden in local or aws.
But at this point I could need some help.
PS: And why I cant find any useful documentatins about the Hibernate naming strategy settings?!? e.g.: strat-setting-A => TableName -> TABLE_NAME etc...
Why do I have to read the code to understand this? (T.T)
EDIT:
Hooray! I have the cause.
My local db config is diffrent. Well its by default: lower_case_table_names=1
So it just ignores CamelCase. But on aws it seems to be set to 0 Which means it takes care of camel case names.
So soultion is easy: Setting my naming strategy to lowercase only!
Just WHERE do I find the docs which config is right?? :-)
Well anyway... better no docs then wrong docs!
SOLUTION:
2 Options:
1 - Configuring the POJOs manually with #Table() decorator.
2 - Removing the hibernate naming setting from the properties (or change it to what ever needed)
PS: Iam still interessted into all setting possibilites if someone know a good doc.

Replace hsqldb with MySQL

I have a Spring REST project configured with hsqldb.
I would like to change it to MySQL.
I have MySQL server installed and running, but I don't know how to modify this pom:
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
PS.: Project im talking about comes as a source code for 'Spring REST' book:
http://www.apress.com/9781484208243
source code download link:
http://www.apress.com/downloadable/download/sample/sample_id/1704/
As far I see you are using Spring Boot on this, so you can easy change the databases changing the drivers dependencies from:
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
To
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
The driver version will be version on parent pom.
Then specify the parameters on properties
spring.datasource.url=jdbc:mysql://localhost:port/yourdb
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver # we can ommit this if we want, Spring Boot will deduce based on the classpath
For more configuration on databases you can see the properties available on appendix here