3 ways you can connect to MongoDB from WildFly - JBoss EAP

In this tutorial we will learn some possible ways to use MongoDB NoSQL Database from within an application server like WildFly or JBoss EAP.

Using Teiid Data Virtualization

The first solution that we will show is Teiid Data Virtualization platform.(The enterprise version of Teiid is called JBoss Data Virtualization platform). Teiid leverages different data sources by means of its Translator component which defines the Connections setting to the data source. In our case, edit the /standalone/configuration/standalone-teiid.xml and include under the "resource-adaptor" subsystem the correct configuration for mongodb:

  <resource-adapters>   
   <resource-adapter id="mongodb">   
    <module slot="main" id="org.jboss.teiid.resource-adapter.mongodb"/>   
    <transaction-support>NoTransaction</transaction-support>   
    <connection-definitions>   
     <connection-definition class-name="org.teiid.resource.adapter.mongodb.MongoDBManagedConnectionFactory"   
       jndi-name="java:/mongoDS"   
       enabled="true"   
       use-java-context="true"   
       pool-name="teiid-mongodb-ds">   
      <!-- MongoDB server list (host:port[;host:port...]) -->   
      <config-property name="RemoteServerList">localhost:27017</config-property>   
      <!-- Database Name in the MongoDB -->   
      <config-property name="Database">test</config-property>   
       <!--    
        Uncomment if your DB is password protected   
       <config-property name="Username">user</config-property>   
       <config-property name="Password">password</config-property>   
       -->    
     </connection-definition>   
    </connection-definitions>   
   </resource-adapter>   
  </resource-adapters>  

The above configuration will create a JCA connection pool to the MongoDB. Save it and start Teeid:

JBOSS_HOME/bin/standalone.sh -c standalone-teiid.xml

Now it is time to create VDB. A Virtual Database definition (VDB) is the primary means to define a connection towards a set of data. The following shows a very simple VDB file which refers to the translator-name and connection-jndi-name:

 <vdb name="MongoQuery" version="1">  
   <model name="MongoQuery">  
     <source name="local" translator-name="mongodb" connection-jndi-name="java:/mongoDS"/>  
       <metadata type="DDL"><![CDATA[  
         CREATE FOREIGN TABLE User (  
           user_id integer,  
           Name varchar(25),  
           Surname varchar(25)  
         ) OPTIONS(UPDATABLE 'TRUE');  
       ]]> </metadata>  
   </model>  
 <vdb>  

Save the the mongodb-vdb.xml in the deployments folder of the application server. In order to test our model, we can use a sample client which is available in the teiid examples quickstart. The sampleclient contains a JDBCClient.java example code that shows a developer the basic connection logic that can be used to connect to a Teiid instance running in a JBoss AS server.

To execute a sql query using the simpleclient, use the following format:

mvn install -Dvdb="MongoQuery" -Dsql="INSERT INTO User(user_id, Name, Surname) VALUES (1, 'Franky', 'Garage');"

This will produce a document like below in the MongoDB database:

{  
  _id: ObjectID("f4948509a8fb2f3bd2f983a0"),  
  user_id: 1,  
  Name: "Franky",  
  Surname: "Garage"  
 }  

Using the MongoDB Java Driver

The other option for using MongoDB is by means of the MongoDB Java Driver which can be used in your applications. This is a quite powerful option as you can use the same features of the native Mongo client, however it raises a dependency to the com.mongodb Java API which will be used in your code. The MongoDB Java driver can be downloaded from the Maven central repository at http://central.maven.org/maven2/org/mongodb/mongo-java-driver/.

Make sure you download the latest stable release of it. Then you can package the Driver along with your applications:

<dependency>
   <groupId>org.mongodb</groupId>
   <artifactId>mongo-java-driver</artifactId>
   <version>2.12.4</version>
</dependency>

If you don't want to package the Driver along with your application then you need to install it as a Module on WildFly:

module add --name=com.mongodb --dependencies="javax.api" --resources=/opt/mongo-2.7.3.jar

And reference it within jboss-deployment-structure.xml:

<jboss-deployment-structure>
   <deployment>
      <dependencies>
         <module name="com.mongodb" />
      </dependencies>
   </deployment>
</jboss-deployment-structure>

Now you can use the MongoDB driver from within your application. Here is for example how to create a CDI Producer for it:

import com.mongodb.MongoClient;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class Producer {
 
@Produces
public MongoClient mongoClient() {
   try {
      return new MongoClient("localhost", 27017);
   } catch (UnknownHostException e) {
      e.printStackTrace();
   }
   return null;
   }
}

Now simply @Inject in your classes the MongoClient as in this example:

@Model
public class BeanDemo {
@Inject
MongoClient mongoClient;
List<Book> listBooks;
 
 
   public List<Book> query() {
 
      DB db = mongoClient.getDB("javaee7");
      DBCollection coll = db.getCollection("bookstore");
      DBCursor cursor = coll.find();

      List<Book> list = new ArrayList<>();
      try {
         while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            . . . .
         }
       } finally {
          cursor.close();
       }
   return list;
   }

Using Hibernate OGM to map MongoDB

Hibernate Object/Grid Mapper (OGM) is a framework which provides Java Persistence (JPA) support for NoSQL solutions. It reuses Hibernate ORM’s engine but persists entities into a NoSQL datastore instead of a relational database. This means you will be writing pure JPA code, which will be handled behind the scenes, by the OGM Engine.

You can read more about Hibernate OGM and MongoDB on this tutorial: Using JPA with MongoDB and WildFly  

Follow us on Twitter