//DBManager.java------------------------------
package usermanager;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
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) {
e.printStackTrace();
}
}
return database;
}
}
//===========================================
//User.java pojo class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package usermanager;
public class User {
private int id;
private String firstName;
private String lastName;
private String email;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
}
//======================================
//Main2.java=== method 1
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package usermanager;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
import com.mongodb.WriteResult;
import static com.sun.xml.internal.fastinfoset.alphabet.BuiltInRestrictedAlphabets.table;
import java.net.UnknownHostException;
//add delete update search.. everything works fine
public class Main2 extends javax.swing.JFrame {
/**
* Creates new form Main
*/
public Main2() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
lblId = new javax.swing.JLabel();
lblFirstName = new javax.swing.JLabel();
lblLastName = new javax.swing.JLabel();
lblEmail = new javax.swing.JLabel();
txtId = new javax.swing.JTextField();
txtFirstName = new javax.swing.JTextField();
txtLastName = new javax.swing.JTextField();
txtEmail = new javax.swing.JTextField();
btnAddUser = new javax.swing.JButton();
btnUpdateUser = new javax.swing.JButton();
btnFindUser = new javax.swing.JButton();
btnDeleteUser = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblId.setText("ID");
lblFirstName.setText("First Name");
lblLastName.setText("Last Name");
lblEmail.setText("Email");
btnAddUser.setText("Add User");
btnAddUser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddUserActionPerformed(evt);
}
});
btnUpdateUser.setText("Update User");
btnUpdateUser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUpdateUserActionPerformed(evt);
}
});
btnFindUser.setText("Find User");
btnFindUser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFindUserActionPerformed(evt);
}
});
btnDeleteUser.setText("Delete User");
btnDeleteUser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteUserActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblId)
.addComponent(lblEmail)
.addComponent(lblLastName)
.addComponent(lblFirstName))
.addGap(69, 69, 69)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtFirstName)
.addComponent(txtLastName)
.addComponent(txtEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
.addComponent(txtId)))
.addGroup(layout.createSequentialGroup()
.addGap(107, 107, 107)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnAddUser)
.addComponent(btnFindUser))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnUpdateUser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnDeleteUser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(95, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(72, 72, 72)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblId)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblFirstName)
.addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblLastName)
.addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblEmail)
.addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAddUser)
.addComponent(btnUpdateUser))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnFindUser)
.addComponent(btnDeleteUser))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnAddUserActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Create user object
User newUser = new User();
newUser.setId(Integer.parseInt(txtId.getText()));
newUser.setFirstName(txtFirstName.getText());
newUser.setLastName(txtLastName.getText());
newUser.setEmail(txtEmail.getText());
// Get connection to the Collection
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("user");
// Insert the Document
BasicDBObject doc = new BasicDBObject();
doc.put("_id", newUser.getId());
doc.put("firstName", newUser.getFirstName());
doc.put("lastName", newUser.getLastName());
doc.put("email", newUser.getEmail());
WriteResult result = col.insert(doc);
System.out.println("Inserted...");
}
private void btnUpdateUserActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Create user object
User newUser = new User();
newUser.setId(Integer.parseInt(txtId.getText()));
newUser.setFirstName(txtFirstName.getText());
newUser.setLastName(txtLastName.getText());
newUser.setEmail(txtEmail.getText());
// Get connection to the Collection
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("user");
// Search
BasicDBObject query = new BasicDBObject();
query.put("_id", newUser.getId());
// Update values
BasicDBObject doc = new BasicDBObject();
doc.put("firstName", newUser.getFirstName());
doc.put("lastName", newUser.getLastName());
doc.put("email", newUser.getEmail());
/*
// Method A
// This will update all values, including all fields and values
WriteResult result = col.update(query, doc);
*/
//Method B
// Update object only with the relevant fields using $set
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", doc);
WriteResult result = col.update(query, updateObj);
System.out.println("Updated...");
}
private void btnFindUserActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Get connection to the Collection
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("user");
// Search
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("_id", Integer.parseInt(txtId.getText()));
DBCursor cursor = col.find(searchQuery);
while (cursor.hasNext()) {
// Access next object
cursor.next();
// Get the whole document printed in the console, if needed
System.out.println(cursor.curr());
// Find by field and set to user object
User newUser = new User();
newUser.setId(Integer.parseInt(cursor.curr().get("_id").toString()));
newUser.setFirstName(cursor.curr().get("firstName").toString());
newUser.setLastName(cursor.curr().get("lastName").toString());
newUser.setEmail(cursor.curr().get("email").toString());
// Show in the form
txtId.setText(String.valueOf(newUser.getId()));
txtFirstName.setText(newUser.getFirstName());
txtLastName.setText(newUser.getLastName());
txtEmail.setText(newUser.getEmail());
}
}
private void btnDeleteUserActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Get connection to the Collection
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("user");
try {
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("_id", Integer.parseInt(txtId.getText()));
col.remove(searchQuery);
System.out.println("Deleted...");
} catch (MongoException e) {
e.printStackTrace();
}
// Empty the form
txtId.setText("");
txtFirstName.setText("");
txtLastName.setText("");
txtEmail.setText("");
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Main2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main2().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnAddUser;
private javax.swing.JButton btnDeleteUser;
private javax.swing.JButton btnFindUser;
private javax.swing.JButton btnUpdateUser;
private javax.swing.JLabel lblEmail;
private javax.swing.JLabel lblFirstName;
private javax.swing.JLabel lblId;
private javax.swing.JLabel lblLastName;
private javax.swing.JTextField txtEmail;
private javax.swing.JTextField txtFirstName;
private javax.swing.JTextField txtId;
private javax.swing.JTextField txtLastName;
// End of variables declaration
}
///===================================================
//method 2 main3.java==not much imp
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package usermanager;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
public class Main3 extends javax.swing.JFrame {
/**
* Creates new form Main
*/
public Main3() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
lblId = new javax.swing.JLabel();
lblFirstName = new javax.swing.JLabel();
lblLastName = new javax.swing.JLabel();
txtId = new javax.swing.JTextField();
txtFirstName = new javax.swing.JTextField();
txtLastName = new javax.swing.JTextField();
btnAddUser = new javax.swing.JButton();
btnUpdateUser = new javax.swing.JButton();
btnFindUser = new javax.swing.JButton();
btnUpsertUser = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblId.setText("ID");
lblFirstName.setText("First Name");
lblLastName.setText("Last Name");
btnAddUser.setText("Add User");
btnAddUser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddUserActionPerformed(evt);
}
});
btnUpdateUser.setText("Update User");
btnUpdateUser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUpdateUserActionPerformed(evt);
}
});
btnFindUser.setText("Find User");
btnFindUser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFindUserActionPerformed(evt);
}
});
btnUpsertUser.setText("Upsert User");
btnUpsertUser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUpsertUserActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblId)
.addComponent(lblLastName)
.addComponent(lblFirstName))
.addGap(69, 69, 69)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtFirstName, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
.addComponent(txtLastName)
.addComponent(txtId)))
.addGroup(layout.createSequentialGroup()
.addGap(107, 107, 107)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnAddUser)
.addComponent(btnFindUser))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnUpsertUser)
.addComponent(btnUpdateUser))))
.addContainerGap(95, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(72, 72, 72)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblId)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblFirstName)
.addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblLastName)
.addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(67, 67, 67)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAddUser)
.addComponent(btnUpdateUser))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnFindUser)
.addComponent(btnUpsertUser))
.addContainerGap(13, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnAddUserActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Get connection to the Collection
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("user");
// Insert the Document
BasicDBObject doc = new BasicDBObject();
doc.put("_id", Integer.parseInt(txtId.getText()));
doc.put("firstName", txtFirstName.getText());
doc.put("lastName", txtLastName.getText());
WriteResult result = col.insert(doc);
}
private void btnUpdateUserActionPerformed(java.awt.event.ActionEvent evt) {
// Get connection to the Collection
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("user");
// Search
BasicDBObject query = new BasicDBObject();
query.put("_id", Integer.parseInt(txtId.getText()));
// Update values
BasicDBObject doc = new BasicDBObject();
doc.put("firstName", txtFirstName.getText());
doc.put("lastName", txtLastName.getText());
// Update object only with the relevant fields using $set
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", doc);
WriteResult result = col.update(query, updateObj);
}
private void btnFindUserActionPerformed(java.awt.event.ActionEvent evt) {
// Get connection to the Collection
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("user");
// Search
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("_id", Integer.parseInt(txtId.getText()));
DBCursor cursor = col.find(searchQuery);
while (cursor.hasNext()) {
// Find by field and show in the form
txtFirstName.setText(cursor.next().get("firstName").toString());
txtLastName.setText(cursor.curr().get("lastName").toString());
}
}
private void btnUpsertUserActionPerformed(java.awt.event.ActionEvent evt) {
// Get connection to the Collection
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("user");
// Search
BasicDBObject query = new BasicDBObject();
query.put("_id", Integer.parseInt(txtId.getText()));
// Update values
BasicDBObject doc = new BasicDBObject();
doc.put("firstName", txtFirstName.getText());
doc.put("lastName", txtLastName.getText());
// Update object only with the relevant fields using $set
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", doc);
// Only difference is last two parameters
/*Parameters:
q - the selection criteria for the update
o - the modifications to apply
upsert - when true, inserts a document if no document matches the update query criteria
multi - when true, updates all documents in the collection that
match the update query criteria, otherwise only updates one
*/
WriteResult result = col.update(query, updateObj, true, false);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Main3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main3().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnAddUser;
private javax.swing.JButton btnFindUser;
private javax.swing.JButton btnUpdateUser;
private javax.swing.JButton btnUpsertUser;
private javax.swing.JLabel lblFirstName;
private javax.swing.JLabel lblId;
private javax.swing.JLabel lblLastName;
private javax.swing.JTextField txtFirstName;
private javax.swing.JTextField txtId;
private javax.swing.JTextField txtLastName;
// End of variables declaration
}