Provide One Datasource With Two Different JNDI Names in Jboss

While testing your JBoss service it can be very handy to use DefaultDS as your data source. However you will probably not want to hardcode this JNDI name into your code, jboss-server.xml, web.xml or persistence.xml (depending on service you write). There you want to use your own "MyAppDS" JNDI name. So wouldn't it be sweet to be able to bind two different JNDI names to the same datasource ?

It is possible and quite simple however I could not really find any good example while Googling the problem. So here is a short description how I solved my problem.

The problem

In a SLSB I’m using JPA to access the database. My persistance.xml has the following defined:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<persistence-unit name="MyApp" transaction-type="JTA">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <jta-data-source>java:MyAppDS</jta-data-source>
      <class>com.example.SomeEntity</class>
      <properties>
         <property name="hibernate.show_sql" value="true"/>
         <property name="hibernate.format_sql" value="true"/>
         <property name="hibernate.hbm2ddl.auto" value="update"/> 
<!--          <property name="hibernate.hbm2ddl.auto" value="create"/>   -->
         <property name="hibernate.cache.use_query_cache" value="false"/>
         <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
      </properties> 
   </persistence-unit>
</persistence>

So how do I use the already defined DefaultDS without having to change the persistance.xml

Solution

The solution is to define a LinkRef from one JNDI name to another. In JBoss this can be done using NamingAlias.

Create your own custome my-ds.xml and place it in the deploy directory.

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
  <mbean code="org.jboss.naming.NamingAlias"
         name="jboss.jca:name=MyAppDS,service=DataSourceBinding">
    <attribute name="FromName">java:MyAppDS</attribute>
    <attribute name="ToName">java:DefaultDS</attribute>
  </mbean>
</datasources>

and your done.