JBoss Datasource configuration

User Rating: 4 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Inactive
 

A Datasource is a Java Naming and Directory Interface (JNDI) object used to obtain a connection from a connection pool to a database. In this tutorial we will learn how to configure connections to Databases using WildFly / JBoss AS 7 / JBoss EAP 6. (If you are using an older version of JBoss skip to the end of this tutorial)

Configuring a Datasource with WildFly and JBoss AS 7 / EAP 6

Datasource configuration can be different depending if you are running the server in Standalone mode or Domain mode.

Configuring a Datasource in Standalone mode

Installing the data source using the Command Line Interface can be used to quickly create the module structure containing the JDBC Driver. It is the recommended option if you plan to create a CLI script so that you can replicate it across your installations. Launch the jboss­cli.sh/ jboss­cli.bat and connect as usual.
The following command will install the com.mysql module creating for you the module directory structure just as we did at the beginning of this chapter:

module add --name=com.mysql --resources=/var/mysql-connector-java-5.1.24-bin.jar --dependencies=javax.api,javax.transaction.api

Next, we need to install the JDBC driver using the above defined module:

/subsystem=datasources/jdbc-driver=mysql:add(driver-name=mysql,driver-module-name=com.mysql)

Finally, install the data source by using the data­source shortcut command, which requires as input the Pool name, the JNDI bindings, the JDBC Connection parameters and finally the security  settings:

data-source add --jndi-name=java:/MySqlDS --name=MySQLPool --connection-url=jdbc:mysql://localhost:3306/mysqlschema --driver-name=mysql --user-name=jboss --password=passwd

The outcome of the CLI session is the following structure in the JBOSS_HOME modules folder:

/home/jboss/wildfly-10.0.0.Final/modules
└───com
└────mysql
└─────main
                   module.xml
                   mysql-connector-java-5.1.24.jar

The modules.xml file has been created with all the requires resources and dependencies needed by
the JDBC Driver:

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.0" name="com.mysql">
   <resources>
      <resource-root path="mysql-connector-java-5.1.24-bin.jar" />
   </resources>
   <dependencies>
      <module name="javax.api" />
      <module name="javax.transaction.api" />
   </dependencies>
</module>

You can check that the datasource has been installed correctly by issuing the following command:

/subsystem=datasources/data-source=MySQLPool:test-connection-in-pool

Configuring a Datasource in Domain mode

When using Domain mode, the datasource needs to be assigned to a server Profile; hence the CLI commands should be adapted. The module installation is not different from standalone mode, you just need to be aware that it requires to be executed on every Host Controller of your domain:

module add --name=com.mysql --resources=/var/mysql-connector-java-5.1.24-bin.jar --dependencies=javax.api,javax.transaction.api

Next, we need to install the JDBC driver on a server Profile:

/profile=full-ha/subsystem=datasources/jdbc-driver=mysql:add(driver-name=mysql,driver-module-name=com.mysql)

Finally, install the data source by using the data­source shortcut command, which requires also the ­­profile additional option:

data-source add --jndi-name=java:/MySqlDS --name=MySQLPool --connection-url=jdbc:mysql://localhost:3306/mysqldb --driver-name=mysql --user-name=jboss
--password=jboss --profile=full-ha

Creating an XA Datasource

If you are going to use an XA Datasource in your applications there are some changes that you need to apply to your CLI scripts. Start as usual by creating the module at first:

module add --name=com.mysql –resources=/var/mysql-connector-java-5.1.24-bin.jar --dependencies=javax.api,javax.transaction.api

Next, install the JDBC driver using the above module:

/subsystem=datasources/jdbc-driver=mysql:add(driver-name=mysql,driver-module-name=com.mysql)

The twist now is to use the xa­data­source shortcut command in order to create the XA Datasource. This command requires that you specify the Datasource name, its JNDI Bindings, the XA Datasource class, the Security settings and, finally, at least one property must be specified (in our case we have specified the Server host name and the Database name):

xa-data-source add --name=MySqlDSXA --jndi-name=java:/MySqlDSXA --driver-name=mysql --xa-datasource-class=com.mysql.jdbc.jdbc2.optional.MysqlXADataSource --user-name=jboss --password=jboss --xa-datasource ---xa-datasource-properties=[{ServerName=localhost},{DatabaseName=mysqlschema}]

Configuring the Datasource attributes

Once created, the data source uses some default settings that might be good for an initial shot; in order to achieve optimal performance you should adjust these values based on your needs. Here is the list of attributes that you can configure with a short description:

  • min­-pool­-size: The minimum number of connections in the pool (default 0)
  • initial­-pool­-size: The initial number of connections to acquire from the database (New since WildFly 9)
  • max­-pool­-size: The maximum number of connections in the pool (default 20)
  • pool­-use­-strict­min: Whether idle connections below the min­pool­size should  be closed
  • pool­-prefill: Attempt to pre­fill the connection pool to the minimum number of connections. This will check your connections as soon as the Datasource is installed.
  • flush­-strategy: Specifies how the pool should be flushed in case of an error. The default one (FailingConnectionOnly) forces destroying only connections with error.
  • idle­-timeout­-minutes: Specifies the maximum time, in minutes, a connection may be idle before being closed. The actual maximum time depends also on the IdleRemover scan time, which is half of the smallest idle­timeout­minutes value of any pool.
  • track­-statements: Whether to check for unclosed statements when a connection is returned to the pool, result sets are closed, a statement is closed or return to the prepared statement cache. Valid values are: "false" ­ do not track statements, "true" ­ track statements and result sets and warn when they are not closed, "nowarn" ­track statements but do not warn about them being unclosed

So how these attributes can affect your applications ? Let's see it from the boot process.
When the application server starts, if you have configured an initial­-pool­-size, the datasource will be eventually filled up with that number of connections. Otherwise, you start with an empty pool. From now on, every time a Connection is requested to the datasource a check is made to see if any idle Connection is available. If not, the application server will attempt to acquire a new database Connection. So, unless the max­-pool­-size has been reached, a new Connection will be created. When a Connection completes its job it becomes idle. A Connection can stay idle up to a maximum number of minutes as specified by the idle­-timeout­-minutes. After that, the Connection is returned to the pool.
The pool­-use-­strict­-min allows for a variation to this rule. If set to true, idle connections are not returned to the pool if you have hit the min-­pool­-size. They will just stay idle, ready to be used by your applications. Here is the min-­pool­-size and max-­pool­-size settings are applied to the MySQL datasource:

/subsystem=datasources/data-source=MySqlDS:write-attribute(name=min-pool-size,value=10)
/subsystem=datasources/data-source=MySqlDS:write-attribute(name=max-pool-size,value=50)

Other tutorials on Datasources and WildFly

Demystifying Datasource JTA and XA settings on JBoss-WildFly

JBoss Datasource cheatsheet

Creating a Datasource on WildFly 9 using templates

Creating a Datasource on JBoss-WildFly using a batch script

Configuring a datasource with PostgreSQL and JBoss/WildFly

Configuring a Datasource with JBoss AS 4 and 5

In order to create a DataSource (so that you can use JDBC connectivity) you need to create a file ending with -ds.xml under the "deploy" directory of your server.

The default Datasource file

The default data source configured with JBoss 4.0 is the HypersonicDB data source. 
Here's the hsqldb-ds.xml that is shipped with jboss : 

<?xml version="1.0" encoding="UTF-8"?>

<datasources>
    <local-tx-datasource>

        <jndi-name>DefaultDS</jndi-name>

        <connection-url>jdbc:hsqldb:${jboss.server.data.dir}${/}hypersonic${/}localDB
        </connection-url>

        <driver-class>org.hsqldb.jdbcDriver</driver-class>

        <user-name>sa</user-name>
        <password></password>

        <min-pool-size>5</min-pool-size>
        <max-pool-size>20</max-pool-size>

        <idle-timeout-minutes>0</idle-timeout-minutes>

        <track-statements />

        <security-domain>HsqlDbRealm</security-domain>

        <prepared-statement-cache-size>32</prepared-statement-cache-size>

        <metadata>
            <type-mapping>Hypersonic SQL</type-mapping>
        </metadata>

        <depends>jboss:service=Hypersonic,database=localDB</depends>

    </local-tx-datasource>

    <mbean code="org.jboss.jdbc.HypersonicDatabase" name="jboss:service=Hypersonic,database=localDB">
        <attribute name="Database">localDB</attribute>
        <attribute name="InProcessMode">true</attribute>
    </mbean>

</datasources>

As you can see from this file, JDBC connectivity uses Connection pools to dispatch Connections. The initial size and the max size of the Connection pool can be configured with <min-pool-size> and <max-pool-size>.

With <idle-timeout-minutes> you can indicate the maximum time a connection may be idle before being closed and returned to the pool. If not specified it's 15 minutes.

<track-statements/> is a debugging feature: it checks that all statements are closed when the connection is returned to the pool: remember to disable it in production environment.

 <security-domain> tells to use the security domain defined in conf/login-config.xml : in our case:  

 <application-policy name="HsqlDbRealm">
    <authentication>
        <login-module
            code="org.jboss.resource.security.ConfiguredIdentityLoginModule"
            flag="required">
            <module-option name="principal">sa</module-option>
            <module-option name="userName">sa</module-option>
            <module-option name="password"></module-option>
            <module-option name="managedConnectionFactoryName">jboss.jca:service=LocalTxCM,name=DefaultDS
            </module-option>
        </login-module>
    </authentication>
</application-policy>

<prepared-statement-cache-size> is the number of prepared statements per connection to be kept open and reused in subsequent requests. They are stored in a LRU cache. The default is 0 (zero), meaning no cache.

Enterprise datasources

I) Local Datasource

This is a sample Oracle local datasource configuration: a local DataSource is one that does not support two phase commit using a java.sql.Driver.

<datasources>
    <local-tx-datasource>
        <jndi-name>OracleDS</jndi-name>
        <connection-url>jdbc:oracle:thin:@youroraclehost:1521:yoursid</connection-url>

        <driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
        <user-name>x</user-name>
        <password>y</password>

        <min-pool-size>5</min-pool-size>
        <max-pool-size>100</max-pool-size>
        <query-timeout>60</query-timeout>
        <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter
        </exception-sorter-class-name>

        <metadata>
            <type-mapping>Oracle9i</type-mapping>
        </metadata>
    </local-tx-datasource>

</datasources>

Notice the <query-timeout> tag which configures the maximum of seconds before a query times out ( avaliable since Jboss 4.0.3). The <exception-sorter-class-name> is used to Check the Oracle error codes and messages for fatal errors.

In order to be able to use a Datasource, you need to install a JDBC Driver. For JBoss AS 7/WildFly users check this tutorial: How to configure a Datasource with JBoss 7 . Of you are using JBoss AS 4/5 it's enough to drop the JDBC Driver in the lib folder of the application server.

II) XA Datasource

This is a sample XA Datasource: XA DataSources support two phase commit using a  javax.sql.XADataSource

<datasources>
    <xa-datasource>
        <jndi-name>XAOracleDS</jndi-name>
        <track-connection-by-tx></track-connection-by-tx>
        <isSameRM-override-value>false</isSameRM-override-value>
        <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource
        </xa-datasource-class>
        <xa-datasource-property name="URL">jdbc:oracle:oci8:@tc
        </xa-datasource-property>
        <xa-datasource-property name="User">scott
        </xa-datasource-property>
        <xa-datasource-property name="Password">tiger
        </xa-datasource-property>

        <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter
        </exception-sorter-class-name>

        <no-tx-separate-pools></no-tx-separate-pools>


        <metadata>
            <type-mapping>Oracle9i</type-mapping>
        </metadata>
    </xa-datasource>

    <mbean
        code="org.jboss.resource.adapter.jdbc.vendor.OracleXAExceptionFormatter"
        name="jboss.jca:service=OracleXAExceptionFormatter">
        <depends optional-attribute-name="TransactionManagerService">jboss:service=TransactionManager
        </depends>
    </mbean>

</datasources>

Notice the <isSameRM-override-value>  set to false to fix problems with Oracle. The element <track-connection-by-tx/>  can be omitted on JBoss 5 where it's enabled by default.
At last, the  <no-tx-separate-pools> means that Oracles XA datasource cannot reuse a connection outside a transaction once enlisted in a global transaction and vice-versa.

Related articles available on mastertheboss.com

How to deploy a DataSource in jboss at application level ?

  Do you need to deploy your DataSource along with your Enterpri

JBoss Datasource HA

This tutorial has been updated for the new release of JBoss Appli

JBoss run out of Connections ?

Have you got No ManagedConnections available error message ? well

How to connect to a DataSource from a remote client?

  If you want to connect to your JBoss Connection Pool from a re

How do I get the list of Datasources available ?

JBOSS AS 4/5 Users You can use either twiddle: $ twiddle.sh que

How to change JBoss Connection pool size dynamically ?

JBoss recipe of the day

Follow us on Twitter