java操做MongoDB數據庫

1:安裝mongodbjava

    (1):下載mongodb,解壓,在安裝目錄中建立data目錄(與bin目錄同級),在data目錄下建立db目錄mongodb

    (2):啓動mongodb。進入cmd命令行工具,進入mongodb安裝目錄下的bin目錄,輸入命令  mongod -dbpath '{HOME}/data/db'數據庫

    (3):打開瀏覽器,輸入:http://localhost:27017,顯示:It looks like you are trying to access MongoDB over HTTP on the native driver port.說明啓動成功。apache

 

2:使用eclipse建立一個maven項目開操做mongodb數據庫。pom.xml文件以下:json

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 3   <modelVersion>4.0.0</modelVersion>
 4   <groupId>com.chu</groupId>
 5   <artifactId>mongotest</artifactId>
 6   <packaging>war</packaging>
 7   <version>0.0.1-SNAPSHOT</version>
 8   <name>mongotest Maven Webapp</name>
 9   <url>http://maven.apache.org</url>
10   <dependencies>
11     <dependency>
12       <groupId>junit</groupId>
13       <artifactId>junit</artifactId>
14       <version>3.8.1</version>
15       <scope>test</scope>
16     </dependency>
17     
18     
19     <dependency>
20         <groupId>org.mongodb</groupId>
21         <artifactId>mongo-java-driver</artifactId>
22         <version>2.10.1</version>
23     </dependency>
24     
25     
26     <dependency>
27         <groupId>org.codehaus.jackson</groupId>
28         <artifactId>jackson-core-asl</artifactId>
29         <version>1.9.9</version>
30     </dependency>
31     <dependency>
32         <groupId>org.codehaus.jackson</groupId>
33         <artifactId>jackson-mapper-asl</artifactId>
34         <version>1.9.9</version>
35     </dependency>
36     
37     
38     
39   </dependencies>
40   <build>
41     <finalName>mongotest</finalName>
42   </build>
43 </project>
View Code

java代碼以下:瀏覽器

 1 package com.mongo.action;
 2 
 3 import java.net.UnknownHostException;
 4 import java.util.List;
 5 
 6 import com.mongo.po.User;
 7 import com.mongo.service.UserService;
 8 
 9 public class UserAction {
10 
11     private UserService userService = new UserService();
12     
13     
14     public void save() throws UnknownHostException{
15         User user = new User();
16         user.setId(1);
17         user.setName("jinhui");
18         user.setAddress("beijing");
19         this.userService.save(user);
20     }
21     
22     public void update()throws UnknownHostException{
23         User user = new User();
24         user.setId(1);
25         user.setName("manman");
26         user.setAddress("hebei");
27         this.userService.update(user);
28     }
29     
30     public List<User> findAll()throws UnknownHostException{
31         return this.userService.findAll();
32     }
33     
34     public void remove()throws UnknownHostException{
35         this.userService.remove(1);
36     }
37     
38     
39     
40     public static void main(String[] args)throws UnknownHostException {
41         UserAction userAction = new UserAction();
42         
43         userAction.save();
44         
45 //        userAction.update();
46         
47 //        userAction.remove();
48         
49         List<User> list = userAction.findAll();
50         for(User user : list){
51             System.out.println(user);
52         }
53     }
54     
55 }
View Code

 

 1 package com.mongo.service;
 2 
 3 import java.net.UnknownHostException;
 4 import java.util.List;
 5 
 6 import com.mongo.dao.UserDao;
 7 import com.mongo.po.User;
 8 
 9 public class UserService {
10 
11     private UserDao userDao = new UserDao();
12     
13     /**
14      * 保存
15      * @param user
16      * @throws UnknownHostException
17      */
18     public void save(User user) throws UnknownHostException{
19         this.userDao.save(user);
20     }
21     
22     
23     
24     /**
25      * 更新
26      * @param user
27      * @throws UnknownHostException
28      */
29     public void update(User user) throws UnknownHostException {
30         this.userDao.update(user);
31     }
32     
33     /**
34      * 查詢全部
35      * @return
36      * @throws UnknownHostException 
37      */
38     public List<User> findAll() throws UnknownHostException{
39         return this.userDao.findAll();
40     }
41     
42     
43     /**
44      * 刪除操做
45      * @param id
46      * @throws UnknownHostException
47      */
48     public void remove(int id) throws UnknownHostException{
49         this.userDao.remove(id);
50     }
51     
52 }
View Code

 

 1 package com.mongo.dao;
 2 
 3 import java.net.UnknownHostException;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 import com.mongo.po.User;
 8 import com.mongodb.BasicDBObject;
 9 import com.mongodb.DB;
10 import com.mongodb.DBCollection;
11 import com.mongodb.DBCursor;
12 import com.mongodb.DBObject;
13 import com.mongodb.Mongo;
14 import com.mongodb.util.JSON;
15 
16 public class UserDao {
17 
18     /**
19      * 保存
20      * @param user
21      * @throws UnknownHostException
22      */
23     public void save(User user) throws UnknownHostException {
24         Mongo mongo = new Mongo();
25         DB myMongo = mongo.getDB("myMongo");
26         DBCollection userCollection = myMongo.getCollection("user");
27 
28         DBObject dbo = (DBObject) JSON.parse(user.toJson());
29         userCollection.insert(dbo);
30     }
31 
32     /**
33      * 更新
34      * @param user
35      * @throws UnknownHostException
36      */
37     public void update(User user) throws UnknownHostException {
38         Mongo mongo = new Mongo();
39         DB myMongo = mongo.getDB("myMongo");
40         DBCollection userCollection = myMongo.getCollection("user");
41 
42         BasicDBObject baseDBO = new BasicDBObject();
43         baseDBO.put("id", user.getId());
44         
45         DBObject newDBO = (DBObject) JSON.parse(user.toJson());
46         
47         userCollection.update(baseDBO, newDBO);
48     }
49     
50     /**
51      * 查詢全部
52      * @return
53      * @throws UnknownHostException 
54      */
55     public List<User> findAll() throws UnknownHostException{
56         Mongo mongo = new Mongo();
57         DB myMongo = mongo.getDB("myMongo");
58         DBCollection userCollection = myMongo.getCollection("user");
59         DBCursor cursor=userCollection.find();
60         
61         List<User> userList = new ArrayList<User>();
62         while(cursor.hasNext()){
63              User user = new User();
64              user.parse(cursor.next());
65              userList.add(user);
66         }
67         return userList;
68     }
69     
70     
71     /**
72      * 刪除操做
73      * @param id
74      * @throws UnknownHostException
75      */
76     public void remove(int id) throws UnknownHostException{
77         Mongo mongo = new Mongo();
78         DB myMongo = mongo.getDB("myMongo");
79         DBCollection userCollection = myMongo.getCollection("user");
80         
81         
82         BasicDBObject baseDBO =new BasicDBObject();
83         baseDBO.put("id", id);
84 
85         //刪除某一條記錄
86         userCollection.remove(baseDBO);
87     }
88     
89 
90 }
View Code

 

 1 package com.mongo.po;
 2 
 3 import com.mongo.utils.JsonUtils;
 4 import com.mongodb.DBObject;
 5 
 6 public class User {
 7 
 8     private int id;
 9     private String name;
10     private String address;
11     
12     
13     public int getId() {
14         return id;
15     }
16     public void setId(int id) {
17         this.id = id;
18     }
19     public String getName() {
20         return name;
21     }
22     public void setName(String name) {
23         this.name = name;
24     }
25     public String getAddress() {
26         return address;
27     }
28     public void setAddress(String address) {
29         this.address = address;
30     }
31     
32     
33     public String toJson(){
34         return JsonUtils.toJson(this);
35     }
36     
37     public void parse(DBObject dbo){
38         this.setId((Integer)dbo.get("id"));
39         this.setName((String)dbo.get("name"));
40         this.setAddress((String)dbo.get("address"));
41     }
42     
43     
44     public String toString(){
45         return "id:"+id+",name:"+name+",address:"+address;
46     }
47 }
View Code

 

  1 package com.mongo.utils;
  2 
  3 import java.io.OutputStream;
  4 
  5 import org.codehaus.jackson.map.ObjectMapper;
  6 import org.codehaus.jackson.type.TypeReference;
  7 
  8 
  9 /**
 10  * Json轉化工具,能夠實現java對象和json字符串之間的互相轉化<br />
 11  * 
 12  */
 13 public class JsonUtils {
 14     static ObjectMapper objectMapper = new ObjectMapper();
 15 
 16     /**
 17      * java 對象轉換爲json 存入流中
 18      * 
 19      * @param obj
 20      * @param out
 21      */
 22     public static String toJson(Object obj) {
 23         String s = "";
 24         try {
 25             s = objectMapper.writeValueAsString(obj);
 26         } catch (Exception e) {
 27             e.printStackTrace();
 28         }
 29         return s;
 30     }
 31 
 32     /**
 33      * java 對象轉換爲json 存入流中
 34      * 
 35      * @param obj
 36      * @param out
 37      */
 38     public static void toJson(Object obj, OutputStream out) {
 39         try {
 40             objectMapper.writeValue(out, obj);
 41         } catch (Exception e) {
 42             e.printStackTrace();
 43         }
 44     }
 45 
 46     /**
 47      * json 轉爲java對象
 48      * 
 49      * @param json
 50      * @param obj
 51      */
 52     @SuppressWarnings({ "rawtypes", "unchecked" })
 53     public static void fromJson(String json, Object obj, Class valueType) {
 54         try {
 55             obj = objectMapper.readValue(json, valueType);
 56         } catch (Exception e) {
 57             e.printStackTrace();
 58         }
 59     }
 60 
 61     /**
 62      * json 轉爲java對象
 63      * @param json
 64      * @param obj
 65      * @param valueTypeRef
 66      */
 67     @SuppressWarnings("rawtypes")
 68     public static void fromJson(String json, Object obj, TypeReference valueTypeRef) {
 69         try {
 70             obj = objectMapper.readValue(json, valueTypeRef);
 71         } catch (Exception e) {
 72             e.printStackTrace();
 73         }
 74     }
 75 
 76     /**
 77      * json 轉爲java對象
 78      * 
 79      * @param json
 80      * @param obj
 81      */
 82     @SuppressWarnings({ "rawtypes", "unchecked" })
 83     public static Object fromJson(String json, Class valueType) {
 84         Object obj = null;
 85         try {
 86             obj = objectMapper.readValue(json, valueType);
 87         } catch (Exception e) {
 88             e.printStackTrace();
 89         }
 90         return obj;
 91     }
 92 
 93     /**
 94      * json 轉爲java對象
 95      * 
 96      * @param json
 97      * @param obj
 98      * @param valueTypeRef
 99      */
100     @SuppressWarnings({ "rawtypes", "hiding" })
101     public static <Object> Object fromJson(String json, TypeReference valueTypeRef) {
102         Object obj = null;
103         try {
104             obj = objectMapper.readValue(json, valueTypeRef);
105         } catch (Exception e) {
106             e.printStackTrace();
107         }
108         return obj;
109     }
110 }
View Code

 

3:使用客戶端工具查看數據app

相關文章
相關標籤/搜索