Create a DataSource by Script in JBoss 7

JBoss AS 7 has a new administrative architecture and simplified command line. Its really much easier to use scripting to create a new JDBC data source.

As you know, creating a data source is a two step process:

  1. Define a JDBC driver. Copy the necessary JAR files so that the servers can find them.
  2. Create a new data source for that driver. Give it a JNDI name and configure the connection pool.

JBoss 7 greatly simplifies the driver creation. Essentially, you deploy the JAR file like a EAR or WAR. If you are using the domain mode, specify the server group for this deployment. The domain controller will automatically copy the JAR file to all the machines. This saves a ton of trouble.

Let’s go through the script line by line:

First, deploy the JDBC driver. If you are in domain mode, use this command. This will distribute the driver to all server groups and copy the JAR file to all machines.

deploy --all-server-groups mysql-connector-java-5.1.21-bin.jar --name=MySQLDriver

If you are in standalone mode, use this command:

deploy mysql-connector-java-5.1.21-bin.jar --name=MySQLDriver

Note that there is no quote around the deployment’s name. Also, JBoss is very picky about what characters you can use. Avoid spaces and any special characters.

Now, create the data source and its connection pool. I broke up the command in multiple lines here to better understand things. But it should be all in a single line in the script.

/subsystem=datasources/data-source="MySqlDS2":add(
  jndi-name="java:/jdbc/MySqlDS2",
  max-pool-size=10,min-pool-size=5,
  driver-name="MySQLDriver",
  connection-url="jdbc:mysql://localhost/test",
  user-name="monty",password="some_pass")

This creates a data source with JNDI name “java:/jdbc/MySqlDS2”. Note: The JNDI name needs to start with either “java:/” or “java:jboss/”.

Finally, enable the data source so you can use it right away.

/subsystem=datasources/data-source=MySqlDS2:enable

If you want to be extra cautious, test the connection right from the script. This step is optional:

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

That’s it.

Now, add all of these lines in a single file (one command per line). Save the file as say script.txt in <JBOSS>/bin folder. Copy the JDBC driver JAR file in the same folder. Then run the script:

./jboss-cli.sh --connect --file=script.txt

If you want to quickly test it out from an application, do that:

try {
    InitialContext ctx = new InitialContext();
    DataSource ds = (DataSource) ctx.lookup("java:/jdbc/MySqlDS2");
    ds.getConnection().close();
} catch (Exception e) {
    e.printStackTrace();
}

One thought on “Create a DataSource by Script in JBoss 7

Leave a reply to eragulin Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.