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:


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:


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">
      <resource-root path="mysql-connector-java-5.1.24-bin.jar" />
      <module name="javax.api" />
      <module name="javax.transaction.api" />

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


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:


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:


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:


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"?>








        <track-statements />



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



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


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">
            <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

<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.






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

        <xa-datasource-property name="URL">jdbc:oracle:oci8:@tc
        <xa-datasource-property name="User">scott
        <xa-datasource-property name="Password">tiger




        <depends optional-attribute-name="TransactionManagerService">jboss:service=TransactionManager


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.

Configuring your datasource to connect to Oracle RAC

Oracle RAC allows multiple computers to run the Oracle RDBMS software simultaneously while accessing a single database  thus providing a clustered database.
In order to benefit from Oracle RAC features like fault tolerance and load balancing all you have to do is configuring the connection url with the list of Oracle hosts which belongs to the cluster.
In this example we are configuring our datasource to connect to a RAC made up of host1 and host2:


Where to put Datasources if JBoss is clustered ?

If you are running a Cluster of JBoss AS 5 servers, position the file -ds.xml in the JBOSS_HOME\server\all\farm\ directory, it will be replicated on all members of the cluster.

Monitoring your Connection Pool (JBoss AS 5)

Each datasource translates into several MBeans that you can interact with in the JMX Console. All the datasource-related objects are in the jboss.jca domain. You can find them by searching through the JMX Console page, or by using jboss.jca:* as the query filter.
Supposing you want to monitor your OracleDS datasource from the previous example: you could use a more specific filter, such as jboss.jca:name=OracleDS,*, to see only the OracleDS entries. In either case, four MBeans will be related to the OracleDS datasource:

  • name=OracleDS ,service=DataSourceBinding

  • name=OracleDS ,service=LocalTxCM

  • name=OracleDS ,service=ManagedConnectionFactory

  • name=OracleDS ,service=ManagedConnectionPool

While each plays a critical role in providing the datasource functionality in JBoss, you are most likely to need to interact with the connection pool. Click the connection pool MBean to expose the management attributes and operations.

In our datasource file we've been using specified a minimum connection pool size of 2 and a maximum pool size of 10. You'll see those values reflected in the MinSize and MaxSize attributes. You can change the values in the running server by adjusting the values and clicking Apply Changes.

Setting the values here affects the connection pool only in memory. To change the configuration permanently, update the datasource file. Try setting the pool sizes there. When you save the file, JBoss will redeploy the datasource and the new pool sizes will be displayed when you reload the page.

You might occasionally want to adjust the pool size to account for usage; you are more likely to be curious how much of the connection pool is being used. The ConnectionCount attribute shows how many connections are currently open to the database.

However, open connections are not necessarily in use by application code. The InUseConnectionCount attribute shows how many of the open connections are in use. Viewing the statistic from the other direction, AvailableConnectionCount shows how much room is left in the pool.

Finally, the MBean has several statistics that track connection pool usage over the pool's lifetime. ConnectionCreatedCount and Connection-DestroyedCount keep running totals of the number of connections created and destroyed by the pool. If IdleTimeout is greater than 0, connections will eventually timeout, be destroyed, and be replaced by fresh connections. This will cause the created and destroyed counts to rise constantly. The MaxConnectionsInUseCount attribute keeps track of the highest number of connections in use at a time.

If you notice anything awkward in the connection pool, or you just want to reset the statistics, you can flush the connection pool using the flush operation on the MBean. This will cause a new connection pool to be created, abandoning the previous connection pool.

A Graph is worth 100 words

or so ! if you read our recent Recipes (and we really appreciate that you are a faithful visitor !) then you know that JBoss Web Console is able to show you graphically the value of many MBeans attribute (those who have a numeric value).
So look for the MBean "name=OracleDS ,service=ManagedConnectionPool", there you can choose to add a graph to any of the attributes: in this picture you can see a sample graph of the JMX Attribute Connection Count

This tutorial can be used to configure a Datasource with releases 4.x-5.x and 6.x of the application server. If you want to configure a Datasource for JBoss AS 7 read this tutorial .



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