Adding to answers, which mention auto-generated database name in Spring Boot 2.3+ – this is the way how to get the generated name into H2 Console programatically in Spring Boot, so that you can keep the generated database name. It basically gets the first H2 database source and updates/generates the H2 Console configuration file ~/.h2.server.properties, which is then loaded by H2 Console when it is first accessed.
Configure pom.xml to use H2 types directly:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>compile</scope>
</dependency>
Enable H2 Console in application.properties (true
is a default value):
spring.h2.console.enabled=true
Code to use auto-generated database name:
import java.io.OutputStream;
import java.sql.Connection;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.sql.DataSource;
import org.h2.engine.Constants;
import org.h2.store.fs.FileUtils;
import org.h2.util.SortedProperties;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Configuration;
@Configuration
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class H2ConsoleDatabaseAutoConfigurator {
@Autowired
public void configure(ObjectProvider<DataSource> dataSource) throws Exception
{
Properties properties = SortedProperties.loadProperties(Constants.SERVER_PROPERTIES_DIR + "/" + Constants.SERVER_PROPERTIES_NAME);
List<String> urls = dataSource.orderedStream().map((available) -> {
try (Connection connection = available.getConnection()) {
if (connection.getMetaData().getURL().startsWith("jdbc:h2:mem:")) {
return connection.getMetaData().getURL() + "|" + connection.getMetaData().getUserName();
} else {
return null;
}
}
catch (Exception ex) {
return null;
}
}).filter(Objects::nonNull).collect(Collectors.toList());
if (urls.size() > 0)
{
for (int i = 0;; i++)
{
String value = properties.getProperty(String.valueOf(i), null);
if (value == null || value.startsWith("Local H2|")) {
properties.setProperty(String.valueOf(i), "Local H2|org.h2.Driver|" + urls.get(0));
break;
}
}
OutputStream out = FileUtils.newOutputStream(
Constants.SERVER_PROPERTIES_DIR + "/" + Constants.SERVER_PROPERTIES_NAME, false);
properties.store(out, "H2 Server Properties");
out.close();
}
}
}
The console will contain the current H2 name as Local H2 menu entry:
The code is a composite of sources from H2 Console and Spring Boot H2 Console Autoconfiguration.