📜 ⬆️ ⬇️

Using MongoDB in Java EE 6



MongoDB is a document-oriented NoSQL database management system that does not require a description of the table schema. More about it can be found at the office. site , and in this article I will describe an example of using MongoDB in a Java EE 6 application.

Let's write a small application that implements select - insert operations in MongoDB. The NetBeans 7.0 environment and the GlassFish application server will be used.

Installation

First, download MongoDB for a specific platform from here .
Then we start the server. To do this, you must run mongod.exe from the bin folder. Before this, you need to create a directory / data / db, which will be used by default for data storage.
When starting the server, you can also specify a different folder for storing data. To do this, you need to specify the --dbpath [folder name] parameter.
')
Creating a project

In NetBeans, we create a WebApplication project. We specify the GlassFish server, the JavaEE version is Java EE 6. Also, select the Enable Contexts and Dependency Injection checkbox and add the JavaServer Faces framework.

To use MongoDB, you need to connect the MongoDB Java Driver to the project.

Code

The application will store and display a list of books. Create a Book class:

import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import javax.enterprise.inject.Model; import javax.validation.constraints.Size; @Model public class Book { @Size(min = 1, max = 20) private String name; @Size(min = 1, max = 20) private String author; @Size(min = 1, max = 20) private String language; private int year; //     public BasicDBObject toDBObject() { BasicDBObject document = new BasicDBObject(); document.put("name", name); document.put("year", year); document.put("language", language); document.put("author", author); return document; } public static Book fromDBObject(DBObject document) { Book b = new Book(); b.name = (String) document.get("name"); b.year = (Integer) document.get("year"); b.language = (String) document.get("language"); b.author = (String) document.get("author"); return b; } } 

Here, the “toDBObject” and “fromDBObject” methods provide conversions from Book to DBObject and vice versa. DBObject is an interface that encapsulates a set of key-value pairs that can be stored in the base. Here is the implementation of this BasicDBObject interface.

We will also create a stateless bean containing all the application logic:

 import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.Stateless; import javax.inject.Inject; import javax.inject.Named; @Stateless @Named public class BookSessionBean { @Inject Book book; private DBCollection bookCollection; @PostConstruct private void initDB() throws UnknownHostException { Mongo mongo = new Mongo(); DB db = mongo.getDB("booksDB"); bookCollection = db.getCollection("books"); if (bookCollection == null) { bookCollection = db.createCollection("books", null); } } public void createBook() { BasicDBObject doc = book.toDBObject(); bookCollection.insert(doc); } public List<Book> getBooks() { List<Book> books = new ArrayList<Book>(); DBCursor cursor = bookCollection.find(); while (cursor.hasNext()) { DBObject dbo = cursor.next(); books.add(Book.fromDBObject(dbo)); } return books; } } 

The database is initialized in the “initDB” method with the @PostConstruct annotation.
The DBCollection collection allows you to perform database queries. Calling the "find" method in the "getBooks" method is equivalent to the SQL query "select * from books". The “find” method returns a “DBCursor” cursor, which can be used as an iterator based on the results of a database query.

It remains only to create pages to add and display data. Change the “index.xhtml” to look like this:

 <h1> Add new book </h1> <h:form> Name: <h:inputText value="#{book.name}" size="20" /> <br/> Year: <h:inputText value="#{book.year}" size="6" /> <br/> Language: <h:inputText value="#{book.language}" size="20" /> <br/> Author: <h:inputText value="#{book.author}" size="20" /> <br/> <h:commandButton actionListener="#{bookSessionBean.createBook()}" action="show" title="Add" value="submit"/> </h:form> 

Add also the “show.xhtml” page to display records from the database:

 <h:form> <h:dataTable value="#{bookSessionBean.books}" var="b"> <h:column><f:facet name ="header">Name</f:facet>#{b.name}</h:column> <h:column><f:facet name ="header">Year</f:facet>#{b.year}</h:column> <h:column><f:facet name ="header">Language</f:facet>#{b.language}</h:column> <h:column><f:facet name ="header">Author</f:facet>#{b.author}</h:column> </h:dataTable> </h:form> 

Result

Running the project, we will see the main page:



After filling in the fields and clicking the submit button, we get to the "show.xhtml" page where all the records in the database are displayed.


Links

Source: https://habr.com/ru/post/123502/


All Articles