How to "allow remote database creation" when using h2 database? - spring-boot

I'm trying to create a Spring Boot project with H2 database, which would be accessible by other programs.
application.properties
spring.datasource.url = jdbc:h2:tcp://localhost:8084/~/./db/tech
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.initialization-mode=always
SpringBootMyApplication.java
#SpringBootApplication
public class SpringBootMyApplication{
public static void main(String[] args) {
SpringApplication.run(SpringBootMyApplication.class, args);
}
#Bean(initMethod = "start", destroyMethod = "stop")
public Server h2Server() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "8084");
}
}
The exception is:
Caused by: org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database "C:/Users/onz03589/db/tech" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200]
How to actually "allow remote database creation"?

You need to add "-ifNotExists" parameter to Server.createTcpServer(). But, again, you shouldn't use it together with "-tcpAllowOthers" unless your port is guarded somehow.

You need to add spring boot starter jpa dependency to enable autoconfiguration for h2 database setup.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

I added these two dependencies in the pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>runtime</scope>
</dependency>
And added below in the Application.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
And it worked for me.
If you have any tables or data to be inserted while creating database. You can do it by putting .sql files under resources directory
Now, you can open your database on
http://localhost:port/h2-console

The reason might be
After you run the server and hit the console the spring.datasource.url is not populated properly. Copy paste the url from application.properties file
You might have made mistake in properties uppercase and lowercase
e.g. I have used
spring.datasource.driverclassname
instead of
spring.datasource.driverClassName
So check the casesensitive property names

Related

h2 localhost url different from testdb

I am using below spring boot config:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
When my spring app comes up, I see the following:
H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:304a69fe-27f6-4271-a5c3-015f06910885'
However if i set the below in property file, i do see testdb being connected:
spring.datasource.url=jdbc:h2:mem:testdb
Can someone please let me know why do i need to explicitly set the url in property file? I had created another spring boot app recently with the exact same config but with spring boot version 2.2.4.RELEASE where h2 connected by default to testdb without setting it in property file.
Thanks!
Reconsider default for spring.datasource.generate-unique-name as the current one makes test cases brittle #16747
commit
This change ensures that each test in a test suite that shares an
application context gets a unique embedded database, to prevent
inconsistent embedded database state between tests.
You can revert to the previous behavior by following setting:
spring.datasource.generate-unique-name=false
Found out that with the latest versions of Spring Boot (2.3+), the H2 database name is randomly generated each time you restart the server. Similar post: springboot 2.3.0 while connecting to h2 database
Update:
As you are using h2 console, you probably have a property called
spring.h2.console.enabled=true
If so then Spring's H2ConsoleAutoConfiguration class gets enabled and it does the auto-configuration as given below. (Check here )
If you are using any of this annotations - #DataJdbcTest, #DataJpaTest and #JdbcTest in your test, then Spring through #AutoConfigureTestDatabase will call TestDatabaseAutoConfiguration, which in turn, by default, will configure an in-memory embedded database instance with an auto generated unique name.
If you want to solve the problem for single test case, please use:
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
If you want this to apply for all test cases, then please have this property in application.yaml
spring:
test:
database:
replace: none

Active profile ignored

Sample code
I have already added "spring.profiles.active=local" in application.properties file
But while running the application it is not able to recognize the profile and running with default profile
application.properties
# Tomcat Server Config
server.port=8071
#Profile Config
spring.profiles.active=local
application-local.properties
# Spring JPA Config
spring.datasource.url=jdbc:postgresql://localhost:5432/User
spring.datasource.username=postgres
spring.datasource.password=amt123`
# Hibernate Config
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings=false
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto=none
"spring.devtools.add-properties" default value is true
Once it is set to false, spring boot disables profile configuration.
For me even if I set the value to true, still profile configuration was not enabled
I fixed this issue by removing the dev-tool dependency and adding it again.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
I am not sure on the internal workflow.
If anyone has a proper explanation for this, please comment

h2database login screen not working in my spring application

I am using h2dabase as in memory database in my application.
I have added following dependency in my pom.xml file.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
Following is my application.properties
spring.application.name=currency-exchange-service
server.port=8000
spring.jpa.show-sql=true
spring.h2.console.enabled=true
Following is the error I am getting on the browser:
To reproduce the error, I've downloaded a fresh Spring boot project with the spring-boot-starter-web and h2 modules. When using your settings, the URL was inaccessible just like your screenshot showed.
The URL did became accessible when I added
spring.h2.console.path=/h2-console to application.properties.

Spring-boot populate H2 database with schema.sql and data.sql

I set up Spring-boot to work with H2 in-memory database
application.properties file is in the /config directory
and it looks like, this file is processed
spring.datasource.url=jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.path=/myconsole
spring.h2.console.enabled=true
spring.datasource.initialize=true
spring.datasource.schema=schema.sql
spring.datasource.data=data.sql
This file is processed and the console appears at /myconsole
But the schema.sql and data.sql are not processed and db is empty.
I placed schema.sql and data.sql files both under /config and /src/main/resources.
SQL language instructions are correct and I can populate the table using console input.
Another strange thing is
even though i name db as
spring.datasource.url=jdbc:h2:mem:mydb
the spring console loads another database testdb
o.s.j.d.e.EmbeddedDatabaseFactory --- Starting embedded database: url='jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
How to load the H2 database correctly?
Resolved the issue.
The spring boot app requires its ownd jdbc dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
NON-boot dependency, that I had, is NOT enough alone:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
Without the "spring-boot-starter-jdbc" dependency
"spring.datasource.url" settings in file "application.properties"
are not processed.
That file is actually processed, but not the jdbc settings.
Spring boot will create its own testdb in the memory, which destroys the data
after closing the application.

logging.config configuration for spring boot

I wanted to configure location of log4j.xml file in my spring boot application.
For that I have added logging.config property to my application.properties configuration, indicating log4j.xml file path.
But seems this property is ignored.
But it should work accorindg to spring boot docs:
logging.config= # location of config file (default classpath:logback.xml for logback)
Have I did something wrong?
Spring Boot includes some starters that can be used if you want to exclude or swap specific technical facets. It's using logback by default, if you're gonna use log4j add spring-boot-starter-log4j in your classpath. For example, with maven it would be something like this:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<version>1.2.4.RELEASE</version>
</dependency>
and for log4j 1.x:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.2.4.RELEASE</version>
</dependency>
Then add logging.config to your application.properties:
logging.config = classpath:path/to/log4j.xml
I find out that in some cases external logging config(logback.xml)is not ignored: when application is started from application folder, it works properly.
Some clarification on this point: application is run through script, which can be called from any place.
I have not yet gone deep and found out why it works in that way, but if I provide config file path as an argument during the start up, it will work. So we just add this argument to running script:
--spring.config.location=/configPath/application.properties
Probably this problem is caused by Spring loading stages.
If you have any idea what is the root cause of this problem , please share:)
According to spring boot docs :
If you are using the starter poms for assembling dependencies that means you have to exclude Logback and then include your chosen version of Log4j instead.
like this :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
</dependency>
I spend few days to understand whether this should even work and I have doubts regarding this. Despite it is clearly mentioned in the documentation how to use Custom Log Configuration, some treat it differently. There many issues regarding this property is not working here and there on spring github issue tracker, like this and this. And another valid point is that logging configuration must be done as earlier as possible to correctly log application initialization. Thus system property looks like most savvy option here. And you can keep it within your application code. The only requirements would be to set it before spring context initialization.
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
// to start from command line
System.setProperty("logging.config", "classpath:portal-log4j2.yaml");
SpringApplication.run(Application.class, args);
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
// to start within container
System.setProperty("logging.config", "classpath:portal-log4j2.yaml");
// this has SpringApplication::run() inside
super.onStartup(servletContext);
}
}
Because all apps in Tomcat web container is loaded within the same JVM, there is no sense to deal with custom logging.config but use single config for the whole container with default file name.

Resources