user2329702
user2329702

Reputation: 479

H2 db file in custom location

I am starting H2 db in embedded mode. By default h2 db file is getting created in users directory. I have requirement of creating in a custom location. The custom location should be read from environment variable ( Example %MY_HOME%= C:\TEST). The database file should be created in c:\TEST. What changes should I make in web.xml to do the same?

Thanks in advance

Upvotes: 0

Views: 2215

Answers (2)

user2329702
user2329702

Reputation: 479

I got an answer for my query. We can set init parameters in two ways. 1) web.xml, Generally everyone uses. 2) contextInitialized will be method called as call back method while tomcat is getting started. In that method you can set the init parameters by using instance of servletContext clas.

Upvotes: 1

Mayur Bhokase
Mayur Bhokase

Reputation: 477

You can add you custom location by setting db.url property of H2.

for example :

If your database name is DBNAME then you can set db.url in web.xml with your custom location in following manner :

jdbc:h2:file:C:\\Test\\DBNAME

If you are using Hibernate in your application then you can build session factory for H2 database in following manner :

private static SessionFactory buildSessionFactory()
{
    String methodName = "buildSessionFactory -->";
    _logger.debug(methodName + Constants.CALLED);
    try
    {
        // Create the SessionFactory from hibernate.cfg.xml
        Configuration configuration = new Configuration();
        URL resourceURL = HibernateUtil.class.getClassLoader().getResource("hibernate.cfg.xml");
        _logger.debug(resourceURL);
        configuration = configuration.configure(resourceURL);
        //Here you can set your custom url for H2 database.
        String url = "jdbc:h2:file:C:\\Test\\DBNAME;MV_STORE=FALSE;MVCC=TRUE;DB_CLOSE_ON_EXIT=TRUE;FILE_LOCK=NO";
        _logger.debug("Database URL " + url);
        _logger.debug("Build Session Factory URL: " + url);
        configuration = configuration.setProperty("hibernate.connection.url", url);
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        _logger.debug("Session factory built");
        _logger.debug(Constants.END);
        return configuration.buildSessionFactory(serviceRegistry);
    }
    catch (Throwable ex)
    {
        _logger.debug("Failed to create session factory");
        _logger.error("Initial SessionFactory creation failed.", ex);
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }
}

Upvotes: 3

Related Questions