Using MongoDB in Java EE 6



    MongoDB is a document-oriented NoSQL DBMS that does not require a description of the table schema. You can learn more about her at the office. site , and in this article I will describe an example of using MongoDB in a Java EE 6 application.

    We will write a small application that implements select - insert operations in MongoDB. NetBeans 7.0 and GlassFish application server will be used.

    Installation

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

    Project creation

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

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

    The code

    The application will store and display a list of books. Create the 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 the Book class to DBObject and vice versa. DBObject is an interface that encapsulates a set of key-value pairs that can be stored in the database. An implementation of this BasicDBObject interface is used here.

    We 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 getBooks() {
            List books = new ArrayList();
            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 annotation @PostConstruct .
    The DBCollection collection allows you to query the database. 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 for adding and displaying data. Change “index.xhtml” to look like this:

    Add new book

    Name:
    Year:
    Language:
    Author:

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

    Name#{b.name}Year#{b.year}Language#{b.language}Author#{b.author}

    Result

    Having launched 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 records in the database are displayed.


    References


    Also popular now: