Java Operations MongoDB Database

Source: Internet
Author: User
Tags install mongodb mongodb tojson

1: Install MongoDB

(1): Download MongoDB, decompression, create the data directory in the installation directory (and the same as the bin directory), in the data directory to create a DB directory

(2): Start MongoDB. Enter the cmd command line tool, enter the bin directory under the MongoDB installation directory, and enter the command Mongod-dbpath ' {home}/data/db '

(3): Open the browser, enter: http://localhost:27017, show: It looks like you are trying to access MongoDB over HTTP on the native driver port. The description starts successfully.

2: Use Eclipse to create a MAVEN project open operation MongoDB Database. Pom.xml files are as follows:

<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/maven-v4_0_0.xsd" > <modelversion >4.0.0</modelVersion> <groupId>com.chu</groupId> <artifactid>mongotest</artifactid > <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>mongotest
      Maven webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</ version> <scope>test</scope> </dependency> <dependency> <groupi D>org.mongodb</groupid> <artifactId>mongo-java-driver</artifactId> <version>2.10.1&lt
    
    
  ;/version> </dependency>  <dependency> <groupId>org.codehaus.jackson</groupId> <artifactid>jackson-core-asl</ artifactid> <version>1.9.9</version> </dependency> <dependency> &LT;GROUPID&G T;org.codehaus.jackson</groupid> <artifactId>jackson-mapper-asl</artifactId> <version>1. 9.9</version> </dependency> </dependencies> <build> <finalname>mo
 Ngotest</finalname> </build> </project>

The


Java code is as follows:

Package com.mongo.action;
Import java.net.UnknownHostException;

Import java.util.List;
Import Com.mongo.po.User;

Import Com.mongo.service.UserService;
	
	
	public class Useraction {private UserService userservice = new UserService ();
		public void Save () throws unknownhostexception{User user = new user ();
		User.setid (1);
		User.setname ("Jinhui");
		User.setaddress ("Beijing");
	This.userService.save (user);
		public void Update () throws unknownhostexception{User user = new user ();
		User.setid (1);
		User.setname ("Manman");
		User.setaddress ("Hebei");
	This.userService.update (user);
	Public list<user> FindAll () throws unknownhostexception{return This.userService.findAll ();
	public void Remove () throws unknownhostexception{This.userService.remove (1);
		
		public static void Main (string[] args) throws Unknownhostexception {useraction useraction = new Useraction ();
		
Useraction.save ();
		
Useraction.update ();
		
		Useraction.remove ();list<user> list = Useraction.findall ();
		for (user user:list) {System.out.println (user);
 }
	}
	
}


Package com.mongo.service;

Import java.net.UnknownHostException;
Import java.util.List;

Import Com.mongo.dao.UserDao;
Import Com.mongo.po.User;

public class UserService {

	private Userdao Userdao = new Userdao ();
	
	/** *
	 Save *
	 @param user
	 * @throws unknownhostexception
	 /public
	void Save (user user) throws unknownhostexception{
		this.userDao.save (user);
	}
	
	
	
	/** *
	 Update
	 * @param user
	 * @throws unknownhostexception
	/public void update (user user) throws unknownhostexception {
		this.userDao.update (user);
	}
	
	/** *
	 Query All
	 * @return *
	 @throws unknownhostexception 
	 /public
	list<user> FindAll () Throws unknownhostexception{return
		this.userDao.findAll ();
	}
	
	
	/** *
	 Delete operation
	 * @param ID
	 * @throws unknownhostexception
	/public void remove (int id) throws unknownhostexception{
		this.userDao.remove (ID);
	}
	
}


Package Com.mongo.dao;
Import java.net.UnknownHostException;
Import java.util.ArrayList;

Import java.util.List;
Import Com.mongo.po.User;
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 Com.mongodb.util.JSON; public class Userdao {/** * save * @param user * @throws unknownhostexception/public void Save (user user) thr
		oWS unknownhostexception {Mongo Mongo = new Mongo ();
		DB Mymongo = Mongo.getdb ("Mymongo");

		Dbcollection usercollection = mymongo.getcollection ("user");
		DBObject dbo = (dbobject) json.parse (User.tojson ());
	Usercollection.insert (dbo); /** * UPDATE * @param user * @throws unknownhostexception/public void update (user user) throws Unknownhostexce
		ption {Mongo Mongo = new Mongo ();
		DB Mymongo = Mongo.getdb ("Mymongo");

		Dbcollection usercollection = mymongo.getcollection ("user"); Basicdbobject basedbo =New Basicdbobject ();
		
		Basedbo.put ("id", User.getid ());
		
		DBObject newdbo = (dbobject) json.parse (User.tojson ());
	Usercollection.update (basedbo, newdbo); /** * Query All * @return * @throws unknownhostexception/public list<user> FindAll () throws Unknownhost
		exception{Mongo Mongo = new Mongo ();
		DB Mymongo = Mongo.getdb ("Mymongo");
		Dbcollection usercollection = mymongo.getcollection ("user");
        
        Dbcursor Cursor=usercollection.find ();
        list<user> userlist = new arraylist<user> ();
             while (Cursor.hasnext ()) {User user = new user ();
             User.parse (Cursor.next ());
        Userlist.add (user);
	return userlist; /** * Delete operation * @param ID * @throws unknownhostexception/public void remove (int id) throws Unknownhostexce
		ption{Mongo Mongo = new Mongo ();
		DB Mymongo = Mongo.getdb ("Mymongo");
		
		
		Dbcollection usercollection = mymongo.getcollection ("user"); Basicdbobject BASEdbo =new basicdbobject ();

        Basedbo.put ("id", id);
	Delete a record usercollection.remove (basedbo);
 }
	

}


Package Com.mongo.po;

Import Com.mongo.utils.JsonUtils;
Import Com.mongodb.DBObject;

public class User {

	private int id;
	private String name;
	Private String address;
	
	
	public int getId () {return
		ID;
	}
	public void setId (int id) {
		this.id = ID;
	}
	Public String GetName () {return
		name;
	}
	public void SetName (String name) {
		this.name = name;
	}
	Public String getaddress () {return address
		;
	}
	public void setaddress (String address) {
		this.address = address;
	}
	
	
	Public String Tojson () {return
		Jsonutils.tojson (this);
	}
	
	public void Parse (DBObject dbo) {
		This.setid ((Integer) dbo.get ("id");
		This.setname ((String) dbo.get ("name"));
		This.setaddress ((String) dbo.get ("Address");
	}
	
	
	Public String toString () {return
		' ID: ' +id+ ', Name: ' +name+ ', Address: ' +address
	}
}


Package com.mongo.utils;

Import Java.io.OutputStream;
Import Org.codehaus.jackson.map.ObjectMapper;


Import org.codehaus.jackson.type.TypeReference;  /** * JSON conversion tool that enables conversion between Java objects and JSON strings <br/> * */public class Jsonutils {static Objectmapper Objectmapper =

	New Objectmapper (); /** * Java object converted to JSON in stream * * @param obj * @param out/public static String Tojson (Object obj) {string s
		= "";
		try {s = objectmapper.writevalueasstring (obj);
		catch (Exception e) {e.printstacktrace ();
	return s; /** * Java object converted to JSON in stream * * @param obj * @param out/public static void Tojson (Object obj, Outputstrea
		m out) {try {objectmapper.writevalue (out, obj);
		catch (Exception e) {e.printstacktrace (); }/** * JSON to Java Object * * @param json * @param obj/@SuppressWarnings ({"Rawtypes", "Unchecked"}) Pub Lic static void Fromjson (String json, Object obj, Class valuetype) {try {obj = Objectmapper.readvAlue (JSON, valuetype);
		catch (Exception e) {e.printstacktrace (); }/** * JSON to Java Object * @param json * @param obj * @param valuetyperef * * @SuppressWarnings ("Rawtypes") p ublic static void Fromjson (String json, Object obj, typereference valuetyperef) {try {obj = Objectmapper.readvalue (
		JSON, VALUETYPEREF);
		catch (Exception e) {e.printstacktrace (); }/** * JSON to Java Object * * @param json * @param obj/@SuppressWarnings ({"Rawtypes", "Unchecked"}) Pub
		Lic static object Fromjson (String json, Class valuetype) {Object obj = null;
		try {obj = Objectmapper.readvalue (JSON, valuetype);
		catch (Exception e) {e.printstacktrace ();
	return obj; /** * JSON to Java Object * * @param json * @param obj * @param valuetyperef/@SuppressWarnings ({"Rawtypes") , "hiding"}) public static <Object> Object Fromjson (String json, typereference valuetyperef) {Object obj = null
		; try {obj = Objectmapper.reaDvalue (JSON, VALUETYPEREF);
		catch (Exception e) {e.printstacktrace ();
	return obj;
 }
}


3: Use the Client tool to view the data:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.