#DataJpaTest doesn't read spring.jpa.* properties while #SpringBootTest does - java

I'm using Spring Boot 2.0.4.RELEASE, and configured src/test/resources/application.yml to be
spring:
jpa:
show-sql: false
hibernate:
dialect: org.hibernate.dialect.SQLServer2012Dialect
ddl-auto: none
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
properties:
hibernate:
generate_statistics: false
show_sql: false
I have a very simple test:
#DataJpaTest
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
#ExtendWith(SpringExtension.class)
public class MyTest {
...
}
The test ignores the properties (can be easily seen as it prints the hibernate statements). Putting the same properties in a application.properties file is working.
Changing the name to application-test.yml and running on profile test didn't help either.
When changing the #DataJpaTest annotation to #SpringBootTest it's working...
It's important to note that the rest of the properties (things related to my application specifically and are not with spring.* prefix are being read and used normally
I do prefer to use a yaml file (like in /src/main/resources) and rather not load a complete #SpringBootTest just for pure JPA tests... Is there anything else that I can configure for this to work?

It is a problem of indentation. properties has to be moved one level to the left.
spring:
jpa:
show-sql: false
hibernate:
dialect: org.hibernate.dialect.SQLServer2012Dialect
ddl-auto: none
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
properties:
hibernate:
generate_statistics: false
show_sql: false
But you could also try this if you use logback.xml for logging config:
<logger name="org.hibernate.stat" level="OFF"/>

#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) - This causes the DataJpaTest to use the same configuration as Spring Boot Main.

Related

Spring boot parameter update model Database don't work

i set the value to update value so that a table will be created in the database automatically corresponding to defined data model.
But it does not work, what it wrong with my properties ?
Database: Mysql
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=2MB
server.port=8081
server.servlet.session.timeout=1200
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=UTC
spring.datasource.username= root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.properties.hibernate.storage.storage_engine=innodb
spring.security.user.name="root"
spring.security.user.password="123"
spring.resources.add-mappings=true
java.sql.SQLSyntaxErrorException: Table 'test.files' doesn't exist
What genereted conflict with "spring.jpa.hibernate.ddl-auto=update"
Make sure the database connection string is valid.
Try changing spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=UTC
The name of your database is "test" but is it really?

How to confgure the PGProperty TCP_KEEP_ALIVE that is available at HikariConfig

How do I configure the property value that tcpkeepalive value is set to true?
I already tried
spring:
datasource:
connection-properties: tcpKeepAlive=true
connectionproperties: tcpKeepAlive=true
However, without success.
HikariConfig does contain a Properties object, but how has the values be defined in the yml file that they are loaded there?
Assuming this property is a connection property of the driver, you need to configure the dataSourceProperties property on hikari. You can do this like:
spring:
datasource:
hikari:
data-source-properties:
tcpKeepAlive: true
Alternatively, you could include the properties in the spring.datasource.url property.

Database did not create with annotation on entity class

I created my entity classes and annotations normally, but hibernate can not generate the tables in my database.
##DataSource settings
spring.datasource.url=jdbc:oracle:thin:#//localhost:1521/BD_GESTION_OPERATION?createDatabaseIfNotExist=true&userSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=system
spring.datasource.password=SeCret
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
##Disabling spring basic security
security.basic.enabled=false
##Start up port
server.port=8082
##Specify DBMS
spring.jpa.database=ORACLE
##Show/Hide SQL queries
spring.jpa.show-sql=false
##Hibernate DDL Auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto=update
##Naming strategy
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy
##Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
Delete old tables. In your application.properties, set property like that (this is default, even you no need declaring it)
spring.jpa.hibernate.ddl-auto=create-drop
You also want to try
spring.jpa.hibernate.ddl-auto=create
Reference https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-initialize-a-database-using-hibernate

spring boot - last profile always used

Spring boot consistently selects the last profile in my application.yml file, no matter how I order them. Please help. If I tear out any more hair, I'll have none left.
Using spring-boot-starter-parent 1.5.1.RELEASE
Maven 3.2.5
There is only one application.yml in my artifact.
I see this in my log: o.s.boot.SpringApplication.logStartupProfileInfo 641 - The following profiles are active: DEV
Here is my application.yml:
server:
context-path: /MyApplicationUI
port: 8480
---
# LOCAL
spring:
profiles: LOCAL
datasource:
driver-class-name: net.sourceforge.jtds.jdbc.Driver
dialect: org.hibernate.dialect.SQLServerDialect
username: #insert username#
encrypted-password: #insert password#
url: jdbc:jtds:sqlserver:blah blah stuff here;
jpa:
database-platform: org.hibernate.dialect.SQLServerDialect
show-sql: true
---
# DEVELOPMENT
spring:
profiles: DEV
datasource:
driver-class-name: net.sourceforge.jtds.jdbc.Driver
dialect: org.hibernate.dialect.SQLServerDialect
username: #insert username#
encrypted-password: #insert password#
url: jdbc:jtds:sqlserver:blah blah stuff here;
jpa:
database-platform: org.hibernate.dialect.SQLServerDialect
show-sql: true
---
# TEST
spring:
profiles: TEST
datasource:
driver-class-name: net.sourceforge.jtds.jdbc.Driver
dialect: org.hibernate.dialect.SQLServerDialect
username: #insert username#
encrypted-password: #insert password#
url: jdbc:jtds:sqlserver:blah blah stuff here;
jpa:
database-platform: org.hibernate.dialect.SQLServerDialect
show-sql: true
I'm loading the encrypted password via my own DatasourceConfig.java:
public class DatasourceConfig {
#Value("${encrypted-password}")
private String encryptedPassword;
/**
* Sets up the datasource with Spring - decrypting password first
*
* #return Datasource
*/
#Bean(name = "dataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource setupDataSource() {
return DataSourceBuilder.create().password(getSecurePassword()).build();
}
/**
* Decrypts encryptedPassword property
*
* #return decryptedPassword
*/
private String getSecurePassword() {
System.out.println("Encrypted password = " + encryptedPassword);
return new AESEncryptionUtils().decryptString(encryptedPassword);
}
...
I do NOT have multiple modules per: spring boot always using the same profile
A thousand thanks-you's to whomever can offer insight.
This YAML file looks more concise:
server:
context-path: /MyApplicationUI
port: 8480
spring:
datasource:
driver-class-name: net.sourceforge.jtds.jdbc.Driver
dialect: org.hibernate.dialect.SQLServerDialect
username: #insert username#
encrypted-password: #insert password#
url: jdbc:jtds:sqlserver:blah blah stuff here;
jpa:
database-platform: org.hibernate.dialect.SQLServerDialect
show-sql: true
profiles:
active: default, local
---
# DEVELOPMENT
spring:
profiles: DEV
datasource:
username: #insert username#
encrypted-password: #insert password#
url: jdbc:jtds:sqlserver:blah blah stuff here;
---
# TEST
spring:
profiles: TEST
datasource:
username: #insert username#
encrypted-password: #insert password#
url: jdbc:jtds:sqlserver:blah blah stuff here;
You don't need to repeat everything all the time, just "the parts" that change between profiles. By default, with this configuration, the profile(s) that will be used are: local and/or default.
If you want to use a different one you have to pass this switch --spring.profiles.active=DEV (or the identifier of the one you want) to the artifact on the command-line (or a script, Docker container, etc).
I couldn't figure out what caused this problem. I had to do a work-around instead. I switched to using property files instead of a yaml. I used a separate property file for each environment, and then explicitly loaded the appropriate property for the environment. I had to do this for my datasourceConfig.java. Not ideal, but it worked.
String env1[] = this.environment.getActiveProfiles();
InputStream propertiesFile = DatasourceConfig.class.getClassLoader()
.getResourceAsStream("application-" + env1[0] + ".properties");
prop.load(propertiesFile);

Envers can't find audit tables

I want to use Envers in my project. The hardest part is to create audit tables. The database structure is created by flyway migrations. Therefore hibernate.hbm2ddl.auto = validate. According to the documentation I should use org.hibernate.envers.tools.hbm2ddl.EnversSchemaGenerator to create schema programmatically. But I didn't find any examples how to do it.
I created flyway migrations for audit tables. However seems like envers can't find them during the start for dev conf. Test conf works just fine. Here is my application.yml for dev:
spring.datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/server?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&connectionCollation=utf8&characterSetResults=UTF-8
username: root
spring.jpa:
database: MYSQL
show-sql: true
hibernate:
ddl-auto: validate
dialect: org.hibernate.dialect.MySQL5Dialect
naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
properties.org.hibernate.envers:
default_schema: server_audit
audit_table_suffix: _history
and Test:
spring:
profiles: test
spring.datasource:
driverClassName: org.h2.Driver
url: jdbc:h2:mem:test;MODE=MySQL;INIT=CREATE SCHEMA IF NOT EXISTS \"public\"\;CREATE SCHEMA IF NOT EXISTS \"SERVER_AUDIT\"
spring.jpa:
database: H2
show-sql: true
hibernate:
ddl-auto: validate
dialect: org.hibernate.dialect.H2Dialect
naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
During the start there is an exception:
java.sql.DatabaseMetaData : HHH000262: Table not found: accounts_history
[lication.main()] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Missing table: accounts_history
Then I changed hbm2ddl.auto = update the output is weird:
java.sql.DatabaseMetaData : HHH000262: Table not found: accounts_history
org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000388: Unsuccessful: create table server_audit.accounts_history
org.hibernate.tool.hbm2ddl.SchemaUpdate : Table 'accounts_history' already exists
and it starts.
UPDATE
Can anyone provide example how to create audit tables using
org.hibernate.envers.tools.hbm2ddl.EnversSchemaGenerator
?

Categories