Specify username, password and connection URL for embedded database in Hibernate/JPA2.1

I have this database defined in java config as follows:

@Bean
public DataSource dataSource() {
    return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .addScript("classpath:/db/sql/create-db.sql")
            .addScript("classpath:/db/sql/insert-data.sql")
            .build();
}

I need to specify username and password for this configuration, but they are hardcoded somewhere deep inside this builder's classes. How can I specify my custom connection details?

If it matters, my full class looks as follows:

@Configuration
public class DatabaseConfig {

    @Resource
    Environment environment;

    @Bean
    public NamedParameterJdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new NamedParameterJdbcTemplate(dataSource);
    }

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .addScript("classpath:/db/sql/create-db.sql")
                .addScript("classpath:/db/sql/insert-data.sql")
                .build();
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
...
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) throws Exception {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
...
        factory.setDataSource(dataSource);
...
        return factory;
    }

    Properties jpaProperties() {
        Properties props = new Properties();
        ...
        return props;
    }
}

and my main configuration file as follows:

@Configuration
@ComponentScan({"com.myapp.conf"})
@EnableAsync
@EnableScheduling
@EnableJpaRepositories(basePackageClasses = {CustomerRepository.class})
@EnableTransactionManagement
@PropertySources({
        @PropertySource("classpath:app.properties")
})
public class ApplicationConfig {
...
}

Here is how I managed to do it: Make a copy of the org.springframework.jdbc.datasource.embedded.SimpleDriverDataSourceFactory that ignores the values set outside:

  final class SimpleDriverDataSourceFactory implements DataSourceFactory {

    private final SimpleDriverDataSource dataSource = new SimpleDriverDataSource();

    @Override
    public ConnectionProperties getConnectionProperties() {
      return new ConnectionProperties() {
        @Override
        public void setDriverClass(Class<? extends Driver> driverClass) {
          dataSource.setDriverClass(driverClass);
        }

        @Override
        public void setUrl(String url) {
          dataSource.setUrl(url);
        }

        @Override
        public void setUsername(String username) {
          // override the sa user
          dataSource.setUsername( "myusername" );
        }

        @Override
        public void setPassword(String password) {
          // override the empty password
          dataSource.setPassword( "mypassword" );
        }
      };
    }

    @Override
    public DataSource getDataSource() {
      return this.dataSource;
    }
  }

Now just use that in your builder:

SimpleDriverDataSourceFactory factory = new SimpleDriverDataSourceFactory();

EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL)
  .setName("mydatabase")
  .setDataSourceFactory( factory )
  .build();
return db;

Not elegant, but it works.

JPA Database Connection (EntityManagerFactory, EntityManager , Specify username, password and connection URL for embedded database in Hibernate/JPA2.1. I have this database defined in java config as follows: Also, don’t forget to change the spring.datasource.username and spring.datasource.password properties as per your MySQL installation. Defining the Domain Model. Let’s first define the embeddable types that will be embedded in the User model.

I don't think that's possible, as you said embedded databases such as hsqldb or h2 have hard coded user name and password ("sa" and "") used to access it from memory (jdbc:hsqldb:mem: for hsqldb).

If you want to change credentials, you should a database like Postgres or mySQL and creating a new datasource (for example with org.apache.commons.dbcp2.BasicDataSource). This way you could set your wanted properties.

Howt to configure Hibernate correctly in our project, The following parameters are supported as part of an ObjectDB connection url: user - for specifying a username in client server mode. password - for specifying  Specifying username/password in a URL It is possible to specify a username (and password!) in a URL. For instance, when you specify an ftp: URL, your browser automatically logs in as user "anonymous" to the ftp server being connected to. You can specify a different username to use with the following syntax: ftp://username@hostname/

You run the database in embedded mode. The current jvm has exclusive access to the db. It's not possible to provide a login in embedded mode. You don't need to provide credentials unless you run in server mode and want to provide remote connections.

See H2 connection modes for detailed explanation.

Hibernate ORM 5.2.18.Final User Guide, validationQuery=SELECT 1 spring.datasource.testOnBorrow=true. Configuration by using code. Firstly, we have database.properties file that contains configuration Driver hibernate.connection.url=jdbc:mysql://localhost:3306/​common? 2 defines the javax.persistence.query.timeout hint to specify default  1. First you will want to create a new API Access account.This account will be the login for everyone from your own site. In this example we will say that the username is "myusers" and the password is "mypassword".

Chapter 2. Setup and configuration, 2.4.1. Component / Embedded; 2.4.2. Multiple embeddable types; 2.4.3. Default value for database column; 4.5. Hibernate 5.2 and later versions require at least Java 1.8 and JDBC 4.2. else if hibernate.connection.url is set → Using Hibernate's built-in (and unsupported) pooling hibernate.connection.​password. But not for IE, which no longer support basic authentication. I implemented this using SSRS 2017, which hides the username and password. I would recommend you test this with an Incognito Browser. Test with and without the password in different Incognito browsers. The one without the password should ask you for the password.

31. Working with SQL Databases, The JPA 2.0 compatible Hibernate EntityManager is built on top of the core of Hibernate 2.2.1. Packaging. The configuration for entity managers both inside an A persistence archive is a JAR file which must define a persistence.xml file that javax.persistence.jdbc.user the user name used for the database connection. Embed a User ID and Password in a URL Frequently, a Web page or an FTP site has protected areas open only to those with a valid login. As you browse to the page, a form appears querying the user id and password.

29. Working with SQL databases, You need a dependency on spring-jdbc for an embedded database to be auto-​configured. In this spring.datasource.username=dbuser spring.datasource.​password=dbpass You should at least specify the URL by setting the spring.​datasource.url property. Hibernate: One of the most popular JPA implementations. It uses a URL along with some credentials to establish a database connection. An object that implements the javax.sql.DataSource interface will typically be registered with JNDI service and can be discovered using it’s JNDI name. A datasource may be used to obtain : standard Connection object; connection which can be used in connection pooling

Comments
  • what if I want to change connection URL? For instance, add some parameters to connection URL?