How to print sql statements with values in spring boot JPA application - mysql

I've Spring Boot Application that uses Spring data JPA and MySQL. With setting SQL properties in application.yml file, I can see the sql but I need to print the values with SQL. How can I achieve that?

You can add these two lines in your application.properties file if you are using JPA and Hibernate. This should enables to write the query on console.
spring.jpa.properties.hibernate.show_sql=true
logging.level.org.hibernate.type.descriptor.sql=trace

You can follow the steps given to achieve this:
Add following to pom.xml
<dependency>
    <groupId>com.github.gavlyukovskiy</groupId>
    <artifactId>p6spy-spring-boot-starter</artifactId>
    <version>1.6.3</version>
</dependency>
 
2. If you are using Eclipse/IntelliJ, Add Program arguments in Run -> Edit Configuration
 -Dspy.properties=/PathToP6SpyDir/spy.properties
 
3. Add following to spy.properties file:
driverlist=com.mysql.jdbc.Driver
appender=com.p6spy.engine.spy.appender.Slf4JLogger
logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
customLogMessageFormat=time %(executionTime)|con %(connectionId)|%(sqlSingleLine)

Spring application.yml:
spring:
jpa:
show-sql: true # show SQL with System.out.println()
properties:
show_sql: true # show SQL with Slf4j
hibernate.format_sql: true # show SQL pretty
logging:
level:
root: INFO
org.hibernate: DEBUG # DEBUG or TRACE is ok

Related

Spring boot JPA error in gradle build from docker

I have a Gradle project, i added jpa to it with:
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.4.3'
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.23'
And in application.properties i have added the following lines:
spring.datasource.url=jdbc:mysql://user:pass#localhost/dbname
spring.datasource.username=null
spring.datasource.password=null
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
### Hibernate Properties
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
It's working fine when the mysql server is hosted on the machine. But when i am building my spring boot application inside the docker with ./gradlew build command, without hosting the mysql its giving me the exception:
oreApplicationTests > contextLoads() FAILED
java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
Caused by: org.springframework.beans.factory.BeanCreationException at AbstractAutowireCapableBeanFactory.java:1796
Caused by: javax.persistence.PersistenceException at AbstractEntityManagerFactoryBean.java:403
Caused by: org.hibernate.exception.JDBCConnectionException at SQLStateConversionDelegate.java:112
Caused by: com.mysql.cj.jdbc.exceptions.CommunicationsException at SQLError.java:174
Caused by: com.mysql.cj.exceptions.CJCommunicationsException at NativeConstructorAccessorImpl.java:-2
Caused by: java.net.UnknownHostException at InetAddress.java:797
I don't want these errors during the build, I only want to turn on the mysql server when i will be using the jars. So i don't want these errors during the compile time.
I ran into a similar error when using MySQL. The solution for me was to add in the dialect to the .properties folder. I figured out the error was coming from JPA not knowing which dialect to use based on the database.
spring.jpa.database-platform=org.hibernate.dialect.{your dialect here}
Also keep in mind tests want to run with an in memory database by default so you need to wire up your tests to run as expected.

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured with Spring, MySql and Gradle

I am working with Spring Boot and MySql. When I launch the application, I get the following error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/*****
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
build.gradle
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
classpath "mysql:mysql-connector-java:$sqlClientVersion"
}
dependencies {
implementation 'mysql:mysql-connector-java:8.0.20'
}
Any help would be really appreciated

Spring Boot DataSource: 'url' attribute is not specified

I am trying to follow this guide
https://spring.io/guides/gs/accessing-data-mysql/
but this guide is for the maven and i am trying the gradle
and getting this error
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
in application.properties i have these things only.
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
I tried all the possible things there is on the SO.
the only deps i have are these
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
Or You will have to prevent Spring boot from automatically configuring the data source by adding this line to the file application.properties.
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
This is kind of an old question but for anyone else coming across this, IF by any chance you are using IntelliJ (as OP does here based on his/her comments) make sure that our beloved IDE recognises your application.properties/application.yml as such by going to File -> Project Structure -> Modules then select your resources file and click on "Resources" from the Mark as: header thing (based on IntelliJ Community Edition 2019.1). Also keep in mind, as no doubt the IDE will certainly notify you, that by reimporting any Maven changes you will need to do this procedure again.
Check the target classpath directory. If the application.properties file didn't exist, then delete the target and rebuild.
I would search the reason somewhere else.
Your error log tells you Reason: Failed to determine a suitable driver class. Please build your project, and check if mysql driver is included in a built jar file. If jar is missing try to change your mysql dependency scope from runtimeOnly to implementation.
The same problem can occur (at least I think so) if you try to run this project from IDE and solution should also help in that case.
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. error is unfortunately very generic and can happen in many different situations. For example last week I had received this error while using oracle Oracle when there where special signs in password which was specified in properties.yaml without double-quotes.
I was having the same problem and solved it by migrating my project that was in version 2.4.x, to 2.3.x.
in IDE / STS (spring tool suit), every thing was working fine
but when made a "project.jar" file,
this was thrown.
unnecessary spaces " " in the "application.yml" file can cause this.
server:
port: 8085
spring:
datasource:
url: jdbc:mysql://localhost:3306/studentdb
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
application:
name: STUDENT-SERVICE
instead of tweaking my "application.yml" file
i simply moved all my statements in "application.yml" file to
"application.properties" file and formatted the statements like required in ".properties".
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/studentdb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format.sql=true
spring.application.name=student-service
server.port=8085
and voilà
(you can add params at the end of url)
(spring.datasource.url=jdbc:mysql://localhost:3306/studentdb?allowPublicKeyRetrieval=true&useSSL=false)
Make sure your pom.xml has the war packaging. It worked for me.
<packaging>war</packaging>
Spring boot has chanegd the url to jdbc-url.
You need to use as below
spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/db_example
Document Link:
https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#data-properties
Stressing that, of course, we would search the documentation for "spring.cloud.config.jdbc-url", but our search should be directly through spring.datasource.hikari.jdbc-url.

Can log4jdbc be used with spring boot?

I have a Spring boot app I'm trying to add database logging to which is better than
spring.jpa.properties.hibernate.show_sql=true
log4jdbc, from
https://github.com/marcosemiao/log4jdbc
seems to be the most up to date fork around, seems to format nicely, fills in parameters and adds timing, exactly what I want.
But when I configure it as stated in the readme, changing
spring.datasource.url=jdbc:mysql://localhost:3306/coindatabase?useSSL=false
to
spring.datasource.url=jdbc:log4jdbc:mysql://localhost:3306/coindatabase?useSSL=false
something seems to not like my reference to mysql and seems to try to fall back to H2:
Caused by: java.lang.RuntimeException: Driver org.h2.Driver claims to not accept jdbcUrl, jdbc:log4jdbc:mysql://localhost:3306/coindatabase?useSSL=false
at com.zaxxer.hikari.util.DriverDataSource.<init>(DriverDataSource.java:106)
Is there some easy way to make this work together?
log4jdbc for spring boot wrapper:
<groupId>com.integralblue</groupId>
<artifactId>log4jdbc-spring-boot-starter</artifactId>
which seems to pull in the implementation from:
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
Additional info:
Don't modify the spring.datasource.url property in your Spring Boot application.properties file; leave the URL as previously defined to access your MYSQL instance.
Instead, after grabbing the com.integralblue maven target, simply set the logging level of choice (ex logging.level.jdbc.sqltiming=info) and your previously defined log4j log will have the DB stuff in it.
See here as was well
You need to use this library in your build.gradle:
// https://mvnrepository.com/artifact/com.integralblue/log4jdbc-spring-boot-starter
compile group: 'com.integralblue', name: 'log4jdbc-spring-boot-starter', version: '2.0.0'
If you get the warning:
"Loading class 'com.mysql.jdbc.Driver'. This is deprecated. The new driver class is 'com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary."
you can set the correct Driver yourself via properties:
log4jdbc.drivers=com.mysql.cj.jdbc.Driver
log4jdbc.auto.load.popular.drivers=false
The documentation for configuration can be found on Github

Hibernate Reverse Engineering with Eclipse and MySql

I'm having the hardest time getting Eclipse to connect and reverse engineer from a MySQL5 database. I can see Eclipse connecting to my MySQL database and can even see the tables through the "Data Source Explorer" view but when I try it after creating Hibernate Console and Configuration files, I get the error:
org.hibernate.console.HibernateConsoleRuntimeException:
Problems while loading database
driverclass (com.mysql.jdbc.Driver)
Problems while loading database
driverclass (com.mysql.jdbc.Driver)
java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
From my simple java project, I start by creating a Hibernate Configuration File (cfg.xml).
Name of file: hibernate.cfg.xml
Session Factory name: org.hibernate.SessionFactory
Database Dialect: org.hibernate.dialect.MySQL5Dialect
Driver Class: com.mysql.jdbc.Driver
Connection Url: jdbc:mysql://localhost:3306/<myDatabaseName>
Default Schema: <myDatabaseName>
Username: correct username
Password: correct password
I also have selected the option to "Create a console Configuration"
At this point, I can see the new configuration listed in my "Hibernate Configuration" perspective/workbench pane. If I try to expand it, I get the earlier listed error.
I don't understand why I can see the database through the 'Data Source Explorer" and even though I'm using the DB connection profile listed in there as part of my configuration, I still get this error.
I also tried to create a new database profile using a manual mysql connector jar (mysql-connector-java-5.1.13-bin.jar) and same end result.
Versions of what I have:
Eclipse version: 3.6.0 aka Helios, Build 20100617 - 1415
MySQL: 5.1.34
Hibernate Tools (from JBoss): HibernateTools-3.3.1.v201006011046R-H111-GA
(placed into Eclipse's 'dropins' folder)
What am I doing wrong in my hibernate configuration setup?
Help!
Your Hibernate Console Configuration doesn't have the MySQL JDBC driver on its classpath, hence the java.lang.ClassNotFoundException:com.mysql.jdbc.Driver. From the reference guide of the Hibernate Tools:
3.4. Creating a Hibernate Console Configuration
...
alt text http://docs.jboss.org/tools/2.1.0.Beta1/hibernatetools/html_single/images/plugins/plugins_3.png
...
Classpath: The classpath for loading POJO and JDBC drivers; only needed if
the default classpath of the Project
does not contain the required classes.
Do not add Hibernate core libraries or
dependencies, they are already
included. If you get ClassNotFound
errors then check this list for
possible missing or redundant
directories/jars.
Include default classpath from project: When enabled the project
classpath will be appended to the
classpath specified above
Does the "associated project" have the MySQL JDBC driver declared as library? If not, then you must add it (either as a project library or in the above tab).