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

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

1) Using the MongoDB Java Driver

The most common way to connect to MongoDB from Java applications is by means of the MongoDB Java Driver which provides a simple and clean interface to perform CRUD operations and advanced searches on your MongoDB documents. This driver also includes a standalone BSON library that you can use to build high-performance encoders and decoders without requiring an intermediate Map instance. Finally, the MongoDB Java Driver also fully implements the Reactive Streams API for providing interop with other reactive streams within the JVM ecosystem.

Installing the MongoDB Java Driver

You can either install MongoDB Java Driver as a WildFly Module, or package it within your application.

To install the MongoDB Java driver as a Module, download it from here first: https://mongodb.github.io/mongo-java-driver/

Then, you can install it from the Command Line as follows:

module add --name=com.mongodb --dependencies="javax.api" --resources=mongo-java-driver-3.12.7.jar

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

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

The other option is to package the MongoDB Java Driver along with your application:

  <dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>${mongodb.driver.version}</version>
  </dependency>

Then, include the MongoDB Driver Version in your Maven Properties:

<mongodb.driver.version>3.12.7</mongodb.driver.version>

Coding a sample CRUD REST Application with MongoDB

As a proof of concept, we will now create a REST Application which uses MongoDB Java Driver to perform CRUD Operations. As we will be using CDI to produce MongoDB objects, the core class is MongoDBProducer which can be used to bootstrap the MongoDatabase:

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;

@ApplicationScoped
public class MongoDBProducer {

    @Produces
    public MongoClient createMongo() {
        return new MongoClient(new ServerAddress(), new MongoClientOptions.Builder().build());
    }

    @Produces
    public MongoDatabase createDB(MongoClient client) {
        return client.getDatabase("testdb");
    }

    public void close(@Disposes MongoClient toClose) {
        toClose.close();
    }
}

As we are now able to produce the com.mongodb.client.MongoDatabase, we can inject it into a Service class which performs the actual CRUD operations:

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.conversions.Bson;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Updates.set;

@ApplicationScoped
public class CustomerService {

    @Inject
    MongoDatabase mongoDB;

    public List<Customer> list(){
        List<Customer> list = new ArrayList<>();
        MongoCursor<Document> cursor = getCollection().find().iterator();

        try {
            while (cursor.hasNext()) {
                Document document = cursor.next();
                Customer customer = new Customer();
                customer.setSurname(document.getString("surname"));
                customer.setName(document.getString("name"));
                customer.setId(document.getLong("id"));
                list.add(customer);
            }
        } finally {
            cursor.close();
        }
        return list;
    }

    public void add(Customer customer){
        Document document = new Document()
                .append("name", customer.getName())
                .append("surname", customer.getSurname())
                .append("id", customer.getId());
        getCollection().insertOne(document);
    }

    public void update(Customer customer){
        // update one document

        Bson filter = eq("id", customer.getId());
        Bson updateOperation = set("name", customer.getName());
        getCollection().updateOne(filter, updateOperation);
    }

    public void delete(Customer customer){
        // delete one document

        Bson filter = eq("id", customer.getId());
        getCollection().deleteOne(filter);
    }
    private MongoCollection getCollection(){
        return mongoDB.getCollection("customers");
    }
}

The rest of the application is trivial. We will add a REST Endpoint to perform the CRUD operations:

import javax.inject.Inject;

import javax.ws.rs.*;
import java.util.List;

@Path("/customer")
@Produces("application/json")
@Consumes("application/json")
public class CustomerEndpoint {

    @Inject CustomerService service;

    @GET
    public List<Customer> list() {
        return service.list();
    }

    @POST
    public List<Customer> add(Customer customer) {
        service.add(customer);
        return list();
    }

    @PUT
    public List<Customer> put(Customer customer) {
        service.update(customer);
        return list();
    }

    @DELETE
    public List<Customer> delete(Customer customer) {
        service.delete(customer);
        return list();
    }
}

That’s all. In order to start MongoDB you can download the latest Community version from: https://www.mongodb.com/try/download/community

To simplify things, we will start MongoDB using Docker with just one line:

docker run -ti --rm -p 27017:27017 mongo:4.0

When MongoDB is running, we can simply build and deploy it on WildFly with:

mvn install wildfly:deploy

Now you can test it, for example adding one Document with:

curl -d '{"id":"1", "name":"Frank", "surname":"Smith"}' -H "Content-Type: application/json" -X POST http://localhost:8080/mongoclient-wildfly/rest/customer

We can then retrieve it as follows:

curl http://localhost:8080/mongoclient-wildfly/rest/customer

The full source code for this example is available here: https://github.com/fmarchioni/mastertheboss/tree/master/nosql/mongodb/mongoclient-wildfly

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

Hibernate OGM talks to NoSQL backends via store-specific dialects. The main repository includes the following dialects:

  • Key/Value: Infinispan (embedded and remote)
  • Document: MongoDB
  • Graph: Neo4j (embedded and remote)

In order to use Hibernate OGM to wrap your NoSQL database, you can just add the hibernate-ogm BOM to your project and then the specific store dialect, such as mongodb:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.hibernate.ogm</groupId>
            <artifactId>hibernate-ogm-bom</artifactId>
            <version>5.4.1.Final</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>jakarta.platform</groupId>
        <artifactId>jakarta.jakartaee-api</artifactId>
        <scope>provided</scope>
        <version>${jakartaee.version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.ogm</groupId>
        <artifactId>hibernate-ogm-mongodb</artifactId>
    </dependency>
</dependencies>

Then, you can use the persistence.xml file just like any JPA application to point to your MongoDB Database:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="mongo-ogm" transaction-type="JTA">
    <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
    <class>com.sample.model.Property</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>
      <property name="hibernate.ogm.datastore.database" value="wildfly"/>
      <property name="hibernate.ogm.datastore.host" value="localhost"/>
      <property name="hibernate.ogm.datastore.provider" value="MONGODB"/>
      <property name="hibernate.ogm.datastore.create_database" value="true" />
    </properties>
  </persistence-unit>
</persistence>

You can find a full example and learn more about Hibernate OGM and MongoDB on this tutorial: http://www.mastertheboss.com/javaee/mongodb/using-jpa-with-mongodb-and-wildfly

3) Using Teiid Data Virtualization (deprecated)

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

MongoDB Java Driver 3.0 Quick reference

Here is a quick reference guide to MongoDB Java Driver version 3.0

How to connect to a local Database and get an handle to DB named “mydb”

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("mydb");

How to get an handle to the Collection named “test”

MongoCollection<Document> collection = database.getCollection("test");

How to create a Document and insert it:

Document doc = new Document("name", "MongoDB")
			   .append("type", "database")
			   .append("count", 1)
			   .append("info", new Document("x", 203).append("y", 102));

collection.insertOne(doc);

How to convert a Document into JSON:

String json = myDoc.toJson();

How to find the first Document in a Collection

Document myDoc = collection.find().first();

How to insert multiple Documents in one shot:

List<Document> documents = new ArrayList<Document>();
for (int i = 0; i < 100; i++) {
	documents.add(new Document("i", i));
}
collection.insertMany(documents);

How to count the number of Documents in a Collection:

System.out.println("total # of documents " + collection.count());

How to iterate over a Collection

MongoCursor<Document> cursor = collection.find().iterator();
try {
	while (cursor.hasNext()) {
		System.out.println(cursor.next().toJson());
	}
} finally {
	cursor.close();
}

How to find one Document whose key matches with a value:

Document myDoc = collection.find(eq("i", 71)).first();

How to find all Documents which are matching a constraint:

MongoCursor<Document> cursor = collection.find(gt("i", 50)).iterator();

How to find all Documents which are matching multiple constraints:

MongoCursor<Document> cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();

How to apply a filter which executes a Callback method defined in a Block class:

Block<Document> printBlock = new Block<Document>() {
	@Override
	public void apply(final Document document) {
		System.out.println(document.toJson());
	}
};
collection.find(gt("i", 50)).forEach(printBlock);

How to use a Projection:

Document myDoc = collection.find().projection(excludeId()).first();

How to update a Document:

collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110)));

How to update multiple Documents:

UpdateResult updateResult = collection.updateMany(lt("i", 100),
		new Document("$inc", new Document("i", 100)));
System.out.println(updateResult.getModifiedCount());

How to delete a Document

collection.deleteOne(eq("i", 110));

How to delete multiple Documents:

DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
System.out.println(deleteResult.getDeletedCount());

How to perform a Bulk write:

List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
writes.add(new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));

collection.bulkWrite(writes);

 

 

How to perform LIKE searches in MongoDB with Java

<p>In order to perform searches just the SQL LIKE expression you need to provide a Regular Expression.</p>
<p>For example, supposing you have the following Document:</p>
<pre class=”brush:text”>{ “_id” : { “$oid” : “5541de4243875f38bcd22ea5”} , “title” : “The Da Vinci Code” , “author” : “Dan Brown” , “type” : “thriller” , “price” : 12 , “copies” : 10}</pre>
<p> Here is an example how to perform this search using the “Vinci” LIKE on the title:</p>
<pre class=”brush:java”>public static void main(String args[]) {
        try {
            // To connect to mongodb server
            MongoClient mongoClient = new MongoClient(“localhost”, 27017);

            DB db = mongoClient.getDB(“javaee7”);

            DBCollection coll = db.getCollection(“bookstore”);

            DBCursor cursor = null;

            BasicDBObject q = new BasicDBObject();
            q.put(“title”, java.util.regex.Pattern.compile(“Vinci”));
            cursor = coll.find(q);

            while (cursor.hasNext()) {
                DBObject obj = cursor.next();

                System.out.println(obj);

            }

            cursor.close();

        } catch (Exception e) {
            System.err.println(e.getClass().getName() + “: ” + e.getMessage());
        }
    }</pre>
<p> </p>

Building Java Enteprise applications using MongoDB

This article is an excerpt from MongoDB for Java Developers book which I have recently published for Packt Publishing. You will find an example Java EE application designed to run on WildFly, using MongoDB as database.

Our application will be a simple bookstore which contains a list of book titles. A start-up class will be in charge to add books to the bookstore. Once executed, the user will be able to purchase books and to perform searches over the titles.

Every application starts from a proper data schema design so our first step will be defining the database structure and then we will create the Java EE interfaces, starting with those directly involved with data CRUD and then moving out to the customer view design.

Designing the schema

Our MongoDB documents will be created in the following storage:

  • Database: javaee7
  • Collection: bookstore

And here is the list of keys we will store in our MongoDB Document:

  • id (automatically generated)
  • title (String)
  • author (String)
  • type (String)
  • price (Integer)
  • copies (Integer)

And here is an example Document that we will use in our application:

{
        "_id" : ObjectId("5541ea47438724845af4cff7"),
        "title" : "The Hobbit",
        "author" : "J.R.R. Tolkien",
        "type" : "Fantasy",
        "price" : 8,
        "copies" : 10
}

All database objects will be created by our Java Enterprise application so right now your only concern will be starting up MongoDB.

Building up the Enterprise project with NetBeans

Our Java Enterprise application will now be created, step by step. 

We will use NetBeans for coding and building our project. Our helping hand will be Maven which is a de facto standard used by Java developers to arrange for a standard application structure, compile, deploy and test it. Being an extensible framework based on plugins, the capabilities of Maven can be even expanded far beyond the above points. First of all, however, we need to configure it so that it can be used in combination with WildFly application server. Next section details it:

Configuring WildFly on NetBeans

Since the release 8.2 of Netbeans you can direclty add the WildFly server to the list of available servers, without the need to download it as a separate plugin. Start NetBeans at first. From the left side of its GUI, select the Services Tab and right-click on Server, as shown by this picture: 

Select Add Server. The server wizard will start: as first option choose €œWildFly Application Server€ from the list of available application server. Click on the Next button to move ahead to the next step:

In the following window select the location where WildFly is installed and pick up the server configuration file to be used (standalone.xml is the default configuration file):

Click on Finish. As you can see from the following picture, now the WildFly application server is enlisted among the available Services by expanding the Servers option:

Creating our Java Enteprise Project

In order to create our project we will use a Maven project. Maven is a popular software and release management tool which buys you:

  • A standard structure for all your Java projects
  • A centralized and automatic management of dependencies

Most development environments are Maven friendly this means that you don€t need to download any additional plugin. Choose from the File menu select New Project. Select within the Maven categories Web Application as displayed by the following window:

Choose Next from the navigation button. The following window will be displayed:

Enter the Project Name, its location on your file system, the GroupId, Version and Package information. Then click on Next. The Group Id in Maven terms is a naming schema used by your Maven project. It generally matches with the root package of your application

In the following window, select as Server WildFly application server and Java EE 7 Web as Java version:

Click on Finish to create the Maven project. The following basic structure should be available in your project view:

Within the Project Files folder a file named pom.xml has been included. This file is the Maven project€s configuration file where you will be able to configure the dependencies on other libraries and also plugins.

Maven plugins are just Java libraries which can be used to empower your Maven with additional capabilities such as compiling, deploying and testing your code

In order to compile your project you will need to specify the dependencies, that is the library which needs to be used by our project. We will start with the following set of libraries in our project:

  • Enterprise Java Beans to code a Startup class in our project
  • Java Server Faces and Context Dependency Injection to code the Web application front-end and the Back end Beans
  • Mongo DB Java Driver for storing data
  • Google€s Gson for transforming JSON Strings into Java objects and viceversa

So here is the list of Dependencies which we need to include in the pom.xml file (you can just replace this with the default one that has been created by NetBeans):

<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.wildfly.bom</groupId>
			<artifactId>jboss-javaee-7.0-with-all</artifactId>
			<version>${version.jboss.bom}</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>
<dependencies>

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

	<dependency>
		<groupId>javax.enterprise</groupId>
		<artifactId>cdi-api</artifactId>
		<scope>provided</scope>
	</dependency>

	<dependency>
		<groupId>org.jboss.spec.javax.faces</groupId>
		<artifactId>jboss-jsf-api_2.2_spec</artifactId>
		<scope>provided</scope>
	</dependency>

	<dependency>
		<groupId>org.jboss.spec.javax.ejb</groupId>
		<artifactId>jboss-ejb-api_3.2_spec</artifactId>
		<scope>provided</scope>
	</dependency>

	<dependency>
		<groupId>org.jboss.spec.javax.annotation</groupId>
		<artifactId>jboss-annotations-api_1.2_spec</artifactId>
		<scope>provided</scope>
	</dependency>

	<dependency>
		<groupId>com.google.code.gson</groupId>
		<artifactId>gson</artifactId>
		<version>2.3.1</version>
	</dependency>

</dependencies>

You can see we have also included a Bill of Materials (BOM) at the top of our dependencies. This is an handy option so that you don€t need to specify each of WildFly€s library version, as they are maintained in the external BOM file

We are done with the Project€s skeleton. Now for the real classes which will make up your application.


The first Java class we will add is named Book and will be used to map MongoDB documents. It contains the same field as the corresponding keys of the document.

package com.packtpub.mongo.chapter4.bean;

public class Book {
 
	String title;
	String author;
	String type;
	int price;
	int copies;

	public Book() { }

	public Book(String title, String author, String type, int price) {
		super();
		this.title = title;
		this.author = author;
		this.type = type;
		this.price = price;
		this.copies = 10;
	}

// Getter and Setters omitted for brevity
}

Now that we have the basic structure to host Mongo documents we need to handle the connection toward MongoDB. Within the Java Enterprise environment there is a better alternative than the following piece of your code around your classes:

MongoClient mongoClient = new MongoClient("localhost", 27017);

Instead of the above, we will create a CDI Producer which will be in charge to create an instance of the MongoClient object and share it with the classes of your application. So add a class named Producer to your project:

package com.packtpub.mongo.chapter4.producer;

public class Producer {
	  @Produces
	  public MongoClient mongoClient() {
	    try {
			return new MongoClient("localhost", 27017);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	    return null;
	  }
}

Producers are an useful addition provided by CDI which can be used when the concrete type of the objects to be injected may vary at runtime or when the objects require some custom initialization that is not performed by the bean constructor

Now we will add the Controller class named BookStore, which receives input from the User Interface and constructs the list of available books:

package com.packtpub.mongo.chapter4.controller;

@Model
public class BookStore implements Serializable {

	@Inject
	MongoClient mongoClient;

	List<Book> listBooks;
	
	String filter;

	@PostConstruct
	private void init() {
		doQuery();
	}

	public void doQuery() {
		listBooks = query();
	}
	public List<Book> query() {
		Gson gson = new Gson();

		DB db = mongoClient.getDB("javaee7");

		DBCollection coll = db.getCollection("bookstore");
		DBCursor cursor = null;
		if (filter == null || filter.trim().length() == 0) {
			cursor = coll.find();	
		}
		else {
			BasicDBObject q = new BasicDBObject();
			q.put("title",  java.util.regex.Pattern.compile(filter));
			cursor = coll.find(q);
		}
		
		
		List<Book> list = new ArrayList();
		try {
			while (cursor.hasNext()) {
				DBObject obj = cursor.next();

				list.add(gson.fromJson(obj.toString(), Book.class));

			}
		} finally {
			cursor.close();
		}
		return list;
	}

	public void buy(Book book) {

		Gson gson = new Gson();

		int copiesLeft = book.getCopies() - 1;
		DB db = mongoClient.getDB("javaee7");

		DBCollection coll = db.getCollection("bookstore");

		BasicDBObject newDocument = new BasicDBObject();
		newDocument.append("$set",
				new BasicDBObject().append("copies", copiesLeft));

		DBObject searchQuery = (DBObject) JSON.parse(gson.toJson(book));
		coll.update(searchQuery, newDocument);

		listBooks = query();

	}

 
}

And now let€s discuss about the most relevant parts of this class: first of all, there is a @Model annotation at the top of it. This is a CDI stereotype which can be used on CDI beans in order to achieve two things:

  • Defines a Request Scope for the class. It means that the class will be created and destroyed according to the user€s request lifecycle
  • Guarantees Expression Language visibility. It means that the class can be used in our UI

Next, we are using the @Inject annotation to let the container provide an instance of the MongoClient class which is actually done by the Producer class we have just coded.

The query and buy methods are our business methods which are respectively used for listing the books and for purchasing them. If you have gone through the Gson section in the previous chapter this code should be quite intuitive for you. Within the query method you will find a search expression which is used to filter among the titles using a Regular Expression pattern. The purpose of this block of code is to provide a SQL LIKE functionality during the search

BasicDBObject q = new BasicDBObject();

q.put("title",  java.util.regex.Pattern.compile(filter));

cursor = coll.find(q);

The list of available books is ultimately maintained into the List<Book> listBooks collection which is updated every time a book is purchased. The above two classes are sufficient to make up the backbone of a Java EE application. We will include one more class to provide some available books when the application is deployed:

package com.packtpub.mongo.chapter4.ejb;

@Singleton
@Startup

public class SchemaSetup {
	@Inject
	MongoClient mongoClient;

	@PostConstruct
	public void createSchema() {
		try {

			DB db = mongoClient.getDB("javaee7");

			DBCollection coll = db.getCollection("bookstore");
			coll.drop();
			coll = db.getCollection("bookstore");

			Book[] book = new Book[5];
			book[0] = new Book("A Tale Of Two Cities", "Charles Dickens","Novel", 10);
			book[1] = new Book("Le Petit Prince", "Antoine de Saint-Exupery","Novel", 8);
			book[2] = new Book("The Da Vinci Code", "Dan Brown", "thriller", 12);
			book[3] = new Book("Think and Grow Rich", "Napoleon Hill","Motivational", 10);
			book[4] = new Book("The Hobbit", "J.R.R. Tolkien", "Fantasy", 8);
			Gson gson = new Gson();

			for (Book b : book) {
				DBObject obj = (DBObject) JSON.parse(gson.toJson(b));
				coll.insert(obj);
			}

		} catch (Exception e) {
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
		}
	}
}

The above class is a Singleton EJB which means that only one instance of this class will be created by the container. Thanks to the @Startup annotation, the createSchema  method, which is annotated with @PostConstruct, will be executed when the application is deployed. 

Inside the createSchema method we first clean up our existing Collection of books and then we create a new Collection by using a combination of MongoDB Driver and Google Gson API.

The server side part is completed. We need one view for displaying the book titles and a couple of buttons to perform respectively a filter on the titles and to purchase a book. Following here is the index.xhtml page which needs to be added to the Project€s Web pages:

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:c="http://java.sun.com/jsp/jstl/core">
 <h:head></h:head>
 
<h:body>

	<h:form id="bookstore">
		<h:panelGrid >
			<h:outputLabel value="Filter title: " style="font-weight:bold" />
			<h:inputText value="#{bookStore.filter}" />
			<h:commandButton actionListener="#{bookStore.doQuery}" styleClass="buttons" value="Search" />
			<h:dataTable value="#{bookStore.listBooks}" var="item" styleClass="table"
				headerClass="table-header"
				rowClasses="table-odd-row,table-even-row">
				<h:column>
					<f:facet name="header">Title</f:facet>
					<h:outputText value="#{item.title}" />
				</h:column>
				<h:column>
					<f:facet name="header">Author</f:facet>
					<h:outputText value="#{item.author}" />
				</h:column>

				<h:column>
					<f:facet name="header">Price</f:facet>
					<h:outputText value="#{item.price}" />
				</h:column>
				<h:column>
					<f:facet name="header">Type</f:facet>
					<h:outputText value="#{item.type}" />
				</h:column>
				<h:column>
					<f:facet name="header">Copies</f:facet>
					<h:outputText   value="#{item.copies}"/>
				</h:column>						

				<h:column>
					<f:facet name="header">Buy</f:facet>
				   <h:commandButton actionListener="#{bookStore.buy(item)}" rendered="#{item.copies > 0}"
						styleClass="buttons" value="Buy" />
				</h:column>							
			</h:dataTable>		 
		</h:panelGrid>

	</h:form>

</h:body>
</html>

The above code contains a few basic JSF components such as an itemText which is an HTML text field used to perform a filter over the title field. The next component is a dataTable that is used to display tabular data contained in the BookStore€s listBooks ArrayList. Within the dataTable every field is referenced through the variable €œitem€ so that we have a tabular view of all our BookStore.

Finally, a Buy button is included which submits the execution to the buy method of the BookStore Bean, passing as argument the item on which the button was clicked.

Just to remind you, the BookStore beans can be referenced from the User Interface as we have tagged it with the @Model annotation. As no specific name has been chosen for this Bean, it will be referenced using its default EL name which is “”bookStore”.


Compiling and deploying the project is just one click away from you, provided that you have added a WildFly application server to your list of Services. Simply right-click on your project and choose €œRun€. A sequence of operations will be triggered:

1. At first WildFly application server will start

2. The Web application will be deployed

3. The index.xhtml page will be displayed

If you are not using NetBeans, simply follow the next section which will detail a generic compilation and deployment procedure that can be used from the shell prompt or wrapped by your Development Environment

Compiling and deploying from the shell

Any Maven project can be compiled and packaged by executing the following goals:

mvn clean install

This will generate an artifact named javaee7-mongodb.war which needs to be deployed on the application server.  The simplest way to do it, is copying the file into the standalone/deployments folder of WildFly.

If you want to automate the distribution of the Web application, we would suggest rather adding Maven€s WildFly plugin which will handle the deployment for you. In order to do that, you need to add the following plugin definition at the bottom of your pom.xml file:

<build>
	<finalName>${project.artifactId}</finalName>
	<plugins>
		<plugin>
			<groupId>org.wildfly.plugins</groupId>
			<artifactId>wildfly-maven-plugin</artifactId>
			<version>1.0.2.Final</version>
		</plugin>
	</plugins>
</build>

 Now with the plugin in place, you can perform compilation, packaging and deployment with a single command:

mvn clean install wildfly:deploy

 A successful execution will terminate with an output like the following one:

INFO: JBoss Remoting version 4.0.3.Final
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 12.269 s
[INFO] Finished at: 2015-04-30T10:39:35+01:00
[INFO] Final Memory: 14M/37M
[INFO] ------------------------------------------------------------------------

Running the application

Whatever is your development environment, you will end up with the Web application deployed on WildFly. So now browse on over the following URL in order to test the application: http://localhost:8080/javaee7-mongodb/index.xhtml

Here is how your application should look like (We have omitted to include the stylesheets used in the index.xhtml page for the sake of brevity. You can find the complete source code of the book in the download area)

You can try how the application works by clicking on the €œBuy€ button which will decrease the count of available book copies. Entering some text into the €œFilter title€ field and clicking on €œSearch€ will restrict the search only to titles containing that text.

      MongoDB for Java Developers
  • A step-by-step tutorial to create leaner and faster applications using MongoDB
  • Reuse the skills you have acquired through Hibernate or Spring to promote your applications to use NoSQL storage
  • Explore the list of libraries that are already available to assist you in developing Java EE applications with MongoDB

Using Hibernate/JPA with MongoDB

Hibernate OGM is a framework that lets you use the power of JPA and Hibernate API with a NoSQL database like MongoDB. To make it fun, we will deploy the JPA MongoDB application on WildFly application server.

First of all some basics. What is Hibernate OGM ? 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.

Hibernate OGM supports a Wide range of backends like MongoDB or Neo4j and has got rich query capabilities such as:

  • Pure JP-QL queries (convert into a native backend query)
  • datastore specific native queries
  • full-text queries, using Hibernate Search as indexing engine

The home of the project is at: http://hibernate.org/ogm/

Building your first Hibernate OGM project.

We will be using a standard Maven webapp-javaee7 project. Most interesting for us is the list of dependencies we need in our project. Let’s start with importing the BOMs for the application server and for Hibernate OGM:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.hibernate.ogm</groupId>
            <artifactId>hibernate-ogm-bom</artifactId>
            <version>5.4.1.Final</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>jakarta.platform</groupId>
        <artifactId>jakarta.jakartaee-api</artifactId>
        <scope>provided</scope>
        <version>${jakartaee.version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.ogm</groupId>
        <artifactId>hibernate-ogm-mongodb</artifactId>
    </dependency>
</dependencies>

The most interesting for us is the hibernate-ogm-mongodb which handles the interaction with MongoDB. Optionally, you can include the Maven’s WildFly plugin:

<build>
	<finalName>${project.artifactId}</finalName>
	<plugins>
		<plugin>
			<groupId>org.wildfly.plugins</groupId>
			<artifactId>wildfly-maven-plugin</artifactId>
			<version>2.0.0.Final</version>
		</plugin>
	</plugins>
</build>

Configuring the database persistence with Hibernate OGM

The main difference compared with a RDBMs approach, is that we won’t specify a datasource reference in the persistence.xml file but just a set of properties that will be used to connecto to the MongoDB datastore: 

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="mongo-ogm" transaction-type="JTA">
    <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
    <class>com.sample.model.Property</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>
      <property name="hibernate.ogm.datastore.database" value="wildfly"/>
      <property name="hibernate.ogm.datastore.host" value="localhost"/>
      <property name="hibernate.ogm.datastore.provider" value="MONGODB"/>
      <property name="hibernate.ogm.datastore.create_database" value="true" />
    </properties>
  </persistence-unit>
</persistence>

We have added the Property class that will be mapped as an Entity. In the properties, the hibernate.ogm.datastore.database specifies the database to be used (you don’t need to create it first.) and hibernate.ogm.datastore.provider specifies the database provider to be used, in our case MONGODB. 

And now the application classes. Here is the EJB that is in charge to handle the persistence:

package com.sample.ejb;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.sample.model.Property;
import javax.ejb.Stateless;

@Stateless
public class PropertyManager {

    @PersistenceContext(unitName = "mongo-ogm")
    private EntityManager em;

    public void save(Property p) {
        em.persist(p);
    }
    public List<Property> queryCache() {
        Query query = em.createQuery("FROM Property p");

        List<Property> list = query.getResultList();
        return list;
    }

}

In the above example we are using JPA-QL to execute searches. At the time of writing there are some limitations when using the JPA-QL as a limited number of constructs are available namely, you are allowed to execute:

• Basic comparisons using “<“, “#”, “=”, “>=” and “>”

• IS NULL and  IS NOT NULL

• The boolean operators  AND ,  OR ,  NOT

• LIKE ,  IN and  BETWEEN

• ORDER BY

if you prefer, you can use instead native queries in your searches, specifying directly the mongodb dialect in your code. Here is an example:

 public List<Property> queryCache() {

	String query1 = "db.Property.find({'value': 'value1'})";
	Query query = em.createNativeQuery(query1, Property.class);
	List<Property> list = query.getResultList();
	return list;
}

And here is the Property class which is an ordinary Entity which is delegating to the underlying datatabase the creation of the id:

package com.sample.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;

@Entity
public class Property {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;

    private String key;

    private String value;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}

 We need some glue between our EJB and the view. Here is the Controller class which is a simple CDI bean:

package com.sample.bean;

import com.sample.ejb.PropertyManager;
import com.sample.model.Property;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.inject.Model;
import javax.inject.Inject;

@Model
public class Controller {

    List<Property> propertyList;

    private String key;
    private String value;

    @PostConstruct
    public void readDB() {
        propertyList = ejb.queryCache();

    }
    @Inject
    PropertyManager ejb;

    public void save() {
        Property p = new Property();
        p.setKey(key);
        p.setValue(value);
        ejb.save(p);
        propertyList.add(p);
        key = "";
        value = "";
    }

    public List<Property> getPropertyList() {
        return propertyList;
    }

    public void setPropertyList(List<Property> propertyList) {
        this.propertyList = propertyList;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}

 Finally, the simple index.xhtml page displaying a form for entering the fields and a datatable:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:c="http://java.sun.com/jsp/jstl/core">
    <h:head>
        <style type="text/css">  
            @import url("css/store.css");
        </style>
    </h:head>
    <h:body>

        <h:form id="jsfexample">
            <h:panelGrid columns="2" styleClass="tablestyle"> 
                <h:outputText value="Hibernate OGM example on WildFly" />
                <br/>
                <h:outputText value="Enter key:" />
                <h:inputText value="#{controller.key}" />

                <h:outputText value="Enter value:" />
                <h:inputText value="#{controller.value}" />

                <h:commandButton actionListener="#{controller.save}"
                                 value="Save key/value" />
            

                <h:messages />


            </h:panelGrid>

            <h:outputText value="No data yet!" rendered="#{empty controller.propertyList}" />
            <br/>

            <h:dataTable value="#{controller.propertyList}" var="item" styleClass="tablestyle" rendered="#{not empty controller.propertyList}">
                <h:column>
                    <f:facet name="header">Key</f:facet>
                    <h:outputText value="#{item.key}" />
                </h:column>
                <h:column>
                    <f:facet name="header">Value</f:facet>
                    <h:outputText value="#{item.value}" />
                </h:column>
            </h:dataTable>
        </h:form>
    </h:body>
</html>

 To compile and deploy the application:

mvn clean install wildfly:deploy

 Here’s the application in action with some nice css addicted:

You can check out the full source code of this application here:

https://github.com/fmarchioni/mastertheboss/tree/master/nosql/mongodb/hibernateogm-mongo

Have fun with MongoDB and JPA!

Developing applications with MongoDB and PrimeFaces on WildFly

This tutorial shows how to build an application which exports/imports data contained in a PrimFaces datatable in MongoDB

MongoDB is a popular noSQL database which can be freely obtained from: http://www.mongodb.org/downloads
Once downloaded, create a script named for example startmongodb.cmd (or equivalent for Linux) which starts the Mongo database, selecting a location for the storage:

mongod --dbpath=C:\MongoDB2.6\data

Now execute the above script and check that it started accepting connections:

2014-08-20T22:21:37.453+0200 [initandlisten] MongoDB starting : pid=6440 port=27017 dbpath=C:\MongoDB2.6\data 64-bit host=francesco-PC
2014-08-20T22:21:37.455+0200 [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2014-08-20T22:21:37.455+0200 [initandlisten] db version v2.6.4
2014-08-20T22:21:37.455+0200 [initandlisten] git version: 3a830be0eb92d772aa855ebb711ac91d658ee910
2014-08-20T22:21:37.455+0200 [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack=’Service Pack 1′)BOOST_LIB_VERSION=1_49
2014-08-20T22:21:37.455+0200 [initandlisten] allocator: system
2014-08-20T22:21:37.455+0200 [initandlisten] options: { storage: { dbPath: “C:\MongoDB2.6\data” } }
2014-08-20T22:21:37.470+0200 [initandlisten] journal dir=C:\MongoDB2.6\data\journal
2014-08-20T22:21:37.471+0200 [initandlisten] recover : no journal files present no recovery needed
2014-08-20T22:21:37.574+0200 [initandlisten] waiting for connections on port 27017

As MongoDB client we will download MongoVue which is available at: http://www.mongovue.com/downloads/
Download it, then install it and execute it (Select to use the Community version at startup). Our initial task will be to connect to the MongoDB using an anonymous connection as follows:

Next, create a new database named wildflyschema:

Done with the database, we will now engineer a simple JSF application enriched by PrimeFaces. This is the Model CDI bean which does most of the Job, that is saving Data in MongoDB (using the saveMongo method) and load data from MongoDB using the loadMongo method.


@Model
public class CarManager {
    List<Car> carList = new ArrayList();
    @Inject
    MongoClient mongoClient;

    @PostConstruct
    public void init() {
        Car car1 = new Car("F40", new Date(), "Ferrari", "Red");
        Car car2 = new Car("Huracan", new Date(), "Lamborghini", "Green");
        Car car3 = new Car("Cayenne", new Date(), "Porsche", "Black");
        carList.add(car1);
        carList.add(car2);
        carList.add(car3);
    }

    public void loadMongo() {

        DB db = mongoClient.getDB("wildflyschema");

        DBCollection table = db.getCollection("cars");

        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("manufacturer", "Ferrari");

        DBCursor cursor = table.find();

        while (cursor.hasNext()) {
            BasicDBObject document = (BasicDBObject) cursor.next();
            Car car = new Car((String) document.get("model"),
                    (Date) document.get("date"),
                    (String) document.get("manufacturer"),
                    (String) document.get("color"));

             carList.add(car);
        }

    }

    public void clear() {
        carList.clear();
    }

    public void saveMongo() {

        DB db = mongoClient.getDB("wildflyschema");

        DBCollection table = db.getCollection("cars");

        for (Car car : carList) {
            BasicDBObject document = new BasicDBObject();
            document.put("color", car.getColor());
            document.put("date", car.getDate());
            document.put("manufacturer", car.getManufacturer());
            document.put("model", car.getModel());
            table.insert(document);
        }

        System.out.println("Done!");

    }

    public List getCarList() {
        return carList;
    }

    public void setCarList(List carList) {
        this.carList = carList;
    }

}

The objects that will be manipulated in this Bean, are Car objects which are statically created in the init() method of the Bean. In the following tutorial I’ll add CRUD capabilities to the Datatable List (contained in carList) so that you can add,delete or modify the content of the datatable.

As you can see, the CarManager gets injected the MongoClient so obviously there is a CDI Producer in this application which follows here:

@ApplicationScoped
public class MongoProducer {
    MongoClient mongoClient;
     @Produces
        public MongoClient create() {
            try {
                mongoClient = new MongoClient();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            return mongoClient; 
        }

        public void close(@Disposes final MongoClient mongoClient) {
            mongoClient.close();
        }
}

The MongoProducer class creates thread-safe instances of MongoClient which are then finalized in the close method that contains a @Disposes annotation.
For the sake of completeness, we will include also the Car class which is a POJO:

public class Car {
    private String model;
    private Date date;
    private String manufacturer;
    private String color;
    
    public Car(String model, Date date, String manufacturer, String color) {
            this.model = model;
            this.date = date;
            this.manufacturer = manufacturer;
            this.color = color;
    }
    // Getters-Setters here
}

Now, the UserInterface which is a generic index.xhtml page containing a Datatable engineered with PrimeFaces components:

<!DOCTYPE html>
<html xmlns="http://www.w3c.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
    <h:form id="jsfexample">


        <p:panelGrid columns="2">
            <f:facet name="header">Cars Availabke</f:facet>

            <p:dataTable id="table" var="car" value="#{carManager.carList}">
                <p:column headerText="Model">
                    <h:outputText value="#{car.model}" />
                </p:column>

                <p:column headerText="Year">
                    <h:outputText value="#{car.date}" />
                </p:column>

                <p:column headerText="Manufacturer">
                    <h:outputText value="#{car.manufacturer}" />
                </p:column>

                <p:column headerText="Color">
                    <h:outputText value="#{car.color}" />
                </p:column>
            </p:dataTable>
            <f:facet name="footer">

                <p:commandButton action="#{carManager.saveMongo}" value="Save" />
                <p:commandButton action="#{carManager.clear}" value="Clear"
                    update="table" />
                <p:commandButton action="#{carManager.loadMongo}" value="Load"
                    update="table" />
            </f:facet>
        </p:panelGrid>

    </h:form>
</h:body>
</html>    

As you can see, besides the Load and Save button, I’ve added a Clear button which empties the list of cars so that we can get it back from MongoDB.
In order to compile and deploy the application, you can use the following pom.xml which contains a dependency to the CDI API, the JSF and PrimeFaces API and, of course, MongoDB Java driver:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sample</groupId>
    <artifactId>DemoMongoDB</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>

    <name>HelloPrime</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.wildfly.bom</groupId>
                <artifactId>jboss-javaee-7.0-with-all</artifactId>
                <version>8.0.0.Final</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.10.1</version>
        </dependency>

        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.jboss.spec.javax.faces</groupId>
            <artifactId>jboss-jsf-api_2.2_spec</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>5.0</version>
        </dependency>

    </dependencies>
    <build>

        <finalName>${project.artifactId}</finalName>

        <plugins>

            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <version>1.0.0.Final</version>
            </plugin>
        </plugins>
    </build>
</project>

Installing MongoDB as a module on WildFly

As it is, the application bundles MongoDB JAR file (mongo-2.10.1.jar) into the WEB-INF/lib folder of your application. If you prefer, you can choose to install it on the application Server as a Module using the following CLI:

module add --name=org.mongodb --resources=C:\MongoDB2.6\mongo-2.10.1.jar 
--dependencies=javax.api,javax.transaction.api

Next, include in your Manifest file (or jboss-deployment-structure.xml) a Dependency on the module. For example:

Dependencies: org.mongodb

Finally, declare the dependency as provided in your pom.xml so it will not be bundled in the web application:

<dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.10.1</version>
            <scope>provided</scope>
</dependency>

So whatever is your choice (to install it as module or not), you can deploy the application as usual with:

mvn wildfly:deploy

Now check the basic use case: Save the data on MongoDB, Clear the table, Load back the data from MongoDB.
You should see again your Datatable populated!


From MongoVUE you can inspect the content of wildflyschema and verify the list of documents contained in it: