Monday, October 13, 2014

mongo NOSql



NoSQL Tutorial
This tutorial aims to create a java based user management application using MongoDB, a cross-platform, document oriented database that provides high performance, high availability and easy scalability. MongoDB works on concept of collection and document.
Prerequisites
1.     MongoDB
2.     MongoVUE
3.     Eclipse with WindowBuilder
Task 1 – Run MongoDB server
1.     Extract MongoDB zip file and move its contents to a location of your choice (eg: c:\mongodb).
2.     MongoDB requires a data folder to store its files. You may create this directory in a location of your choice. The default location for the MongoDB data directory is c:\data\db.
3.     Open up a command prompt and navigate to the bin directory in the mongodb installation folder.
4.     Run mongod.exe by using the following command:
mongod.exe --dbpath "C:\mondogb\data"
 
This will show waiting for connections message on the console output which indicates that the mongod.exe process is running successfully.


Task 2 – Create new database and collection for storing user data
1.     Connect to MongoDB server using MongoVUE.
2.     Create new database by right clicking on the server node and selecting “Add Database”. Name the new database as “usermanager”.
3.     Add new collection to usermanager database by right clicking on the database node and selecting “Add Collection”. Name the new collection as “user”.
Task 3 – Create client application
1.     Open Eclipse and create a new java project.
a.     Select File > New > Project.
b.     Expand ‘Java’ node and select ‘Java Project’. Click ‘Next’.
c.      Name the project as ‘UserManager’ and click ‘Finish’.
2.     Add MongoDB Java driver to the classpath.
a.     Right click project node and select ‘Properties’.
b.     Select ‘Java Build Path’ and go to ‘Libraries’ tab.
c.      Click on ‘Add Externam JARs’ button and browse for the jar file.
d.     Click ‘OK’ to close the window.
3.     Add ‘DBManager’ singleton class for managing database connections
a.     Right click src node > New > Class.
b.     Name the new class as DBManager.
c.      Click ‘Finish’.
d.     Add the following code to the new class:

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.MongoClient;


public class DBManager {
      
       private static DB database;
      
       public static DB getDatabase() {
              if(database == null) {
                     MongoClient mongo;
                     try {
                           mongo = new MongoClient("localhost", 27017);
                           database = mongo.getDB("usermanager");
                     } catch (UnknownHostException e) {
                           // TODO Auto-generated catch block
                           e.printStackTrace();
                     }
              }
              return database;
       }
}

 










4.     Create User entity class.
a.     Add a new class and name it as ‘User’.
b.     Add the following code to the User class:
package lk.sliit.usermanager.model;

public class User {

       private int id;
       private String firstName;
       private String lastName;
       private String email;
      
       public int getId() {
              return id;
       }
       public void setId(int id) {
              this.id = id;
       }
       public String getFirstName() {
              return firstName;
       }
       public void setFirstName(String firstName) {
              this.firstName = firstName;
       }
      

public String getLastName() {
              return lastName;
       }
       public void setLastName(String lastName) {
              this.lastName = lastName;
       }
       public String getEmail() {
              return email;
       }
       public void setEmail(String email) {
              this.email = email;
       }
}
 











5.     Add a new jFrame to the project and name it as ‘Main’
a.     Right click on src node and select New > Other.
b.     Search for ‘jFrame’ and click ‘Next’.
c.      Name the new jFrame as ‘Main’ and click ‘Finish’.
6.     Design the following user interface using the design tool



7.     Code for the ‘Add User’ button is given below:
btnAddUser.addActionListener(new ActionListener() {
                     public void actionPerformed(ActionEvent arg0) {
                           User newUser = new User();
                            newUser.setId(Integer.parseInt(txtId.getText()));
                           newUser.setFirstName(txtFirstName.getText());
                           newUser.setLastName(txtLastName.getText());
                           newUser.setEmail(txtEmail.getText());
                          
                           DBObject doc = createDBObject(newUser);
                           DB userDB = DBManager.getDatabase();
                           DBCollection col = userDB.getCollection("user");
                           WriteResult result = col.insert(doc);
                     }
              });
        private static DBObject createDBObject(User user) {
               BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();
                                       
               docBuilder.append("_id", user.getId());
               docBuilder.append("firstName", user.getFirstName());
               docBuilder.append("lastName", user.getLastName());
               docBuilder.append("email", user.getEmail());
               return docBuilder.get();
           }
 















MYAPP
viewUser

add table and type code

 //   public ViewUser() {
     //   initComponents();
        viewUserData();

    //}

    public void viewUserData() {
        DefaultTableModel model = new DefaultTableModel();

        model.addColumn("ID");
        model.addColumn("First Name");
        model.addColumn("Last Name");
        model.addColumn("Email");

        DB userDB = DBManager.getDatabase();
        DBCollection col = userDB.getCollection("user");

        DBCursor cursor = col.find();

        while (cursor.hasNext()) {
            DBObject user = (DBObject) cursor.next();
            model.addRow(new Object[]{user.get("_id"), user.get("firstName"), user.get("lastName"), user.get("email")});

        }
        jTable1.setModel(model);
    }

manageUser
fill combobox
//public manageUser() {
//        initComponents();
        fillID();

//    }

    public void fillID() {
        DB userDB = DBManager.getDatabase();
        DBCollection col = userDB.getCollection("user");

        DBCursor cursor = col.find();

        while (cursor.hasNext()) {
            DBObject user = (DBObject) cursor.next();
            jComboBox1.addItem(user.get("_id"));
        }
    }

Combobox change event should select
private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {                                           
        // TODO add your handling code here:
        DB userDB = DBManager.getDatabase();
        DBCollection col = userDB.getCollection("user");

        DBCursor cursor = col.find();

        while (cursor.hasNext()) {
            DBObject user = (DBObject) cursor.next();
            int seletedID = Integer.parseInt(jComboBox1.getSelectedItem().toString());
            if (Integer.parseInt(user.get("_id").toString()) == seletedID) {

                jTextField1.setText(user.get("_id").toString());
                jTextField2.setText(user.get("firstName").toString());
                jTextField3.setText(user.get("lastName").toString());
                jTextField4.setText(user.get("email").toString());

            }
        }
    }                     

Update user
try {
            DB userDB = DBManager.getDatabase();
            DBCollection col = userDB.getCollection("user");

            BasicDBObject query = new BasicDBObject("_id", new BasicDBObject("$eq", Integer.parseInt(jTextField1.getText())));

            BasicDBObject newDocument = new BasicDBObject();
            newDocument.put("firstName", jTextField2.getText());
            newDocument.put("lastName", jTextField3.getText());
            newDocument.put("email", jTextField4.getText());

            BasicDBObject updateObj = new BasicDBObject();
            updateObj.put("$set", newDocument);

            col.update(query, updateObj, false, true);

            JOptionPane.showMessageDialog(rootPane, "User Update SucessFully...!");

            jTextField1.setText("");
            jTextField2.setText("");
            jTextField3.setText("");
            jTextField4.setText("");

        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "Please Select User");
        }

Delete user
try {
            DB userDB = DBManager.getDatabase();
            DBCollection col = userDB.getCollection("user");

            BasicDBObject query = new BasicDBObject("_id", new BasicDBObject("$eq", Integer.parseInt(jTextField1.getText())));
            col.remove(query);

            JOptionPane.showMessageDialog(rootPane, "User Delete SucessFully...!");
            this.setVisible(false);
            this.dispose();
            manageUser mange = new manageUser();
            mange.setVisible(true);

        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "Please Select User");
        }

No comments:

Post a Comment