Yordan Borisov
Yordan Borisov

Reputation: 1652

Dynamically datasource with hibernate and netbeans

How I can create web application project which is loading the jndi datasource set in the server configuration? I want to make the web application independent from the server and the database. Is it possible.

Upvotes: 1

Views: 409

Answers (1)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153690

  1. You create the DataSource in your web/application server and expose it through JNDI

  2. You configure the following hibernate property:

     <property name="hibernate.connection.datasource">java:comp/env/jdbc/MyDataSource</p>
    

This way the application is decoupled from the JNDI provider. Even the JNDI url can be configured using a Maven property, so switching to an application server (that uses a different JNDI resource pattern) is just a mater of adding a new Maven profile.

One better approach is to set up the DataSource in your application configuration.

@Autowired
private DataSource dataSource;
...
properties.put("hibernate.connection.datasource", dataSource);

This way you can use any connection pooling framework, like the fastest connection pooling framework, HikariCP.

You can even set up DataSource proxies, like:

  • datasource-proxy, to log SQL queries with PreparedStatement parameters
  • FlexyPool, to monitor connection pooling usage and adjust the pool size using adapting startegies

Upvotes: 2

Related Questions