Spring Data MongoDB 2: add and delete operations, springmongodb

Source: Internet
Author: User

Spring Data MongoDB 2: add and delete operations, springmongodb
I. introduction The Spring Data MongoDB project provides integration with the MongoDB document database. Spring provides org. springframework. orm. hibernate3.HibernateTemplate implements CRUD operations on Data. Spring Data MongoDB provides org. springframework. data. mongodb. core. mongoTemplate performs CRUD operations on MongoDB, including CRUD operations between the integrated object ing file and POJO.

Today, we will introduce how to add and delete MongoDB using Java code.

2. Add

Spring Data MongoDB's document template provides two storage methods: save and insert:

(1) save: When we add a document, if there is a document with the same _ ID, it will overwrite the original one.

(2) insert: when adding a document, if there is an identical _ ID, the addition will fail.

 

 1. Next we will introduce the specific syntax of the two methods respectively.

 

(1) Save Method

Method:

1) void save (Object objectToSave) saves the document to the default set.

2) void save (Object objectToSave, String collectionName) to save the specified set.

(2) Insert Mode

Method:

1) void insert (Object objectToSave) saves the document to the default set.

2) void insertAll (Object objectsToSave) is added to the default set in batches.

3) void insert (Object objectToSave, String collectionName) stores the specified set.


2. Add MongoDB using Spring

We introduced the setup of Spring Data MongoDB in the previous article. Here we will not introduce it in detail.

(1) Introduce interfaces and implementation methods


Step 1: implement a basic interface, which is a common MongoBase. java class. 

Public interface MongoBase <T> {// insert add public void insert (T object, String collectionName); // save add public void save (T object, String collectionName ); // Add public void insertAll (List <T> object) in batches );}

Step 2: The structure of the implementation document is also an entity class.

We have two entity classes here: the order class (Orders. java) and the corresponding order details class (Item. java). Here we implement embedded documents. If there is no embedded document structure, you only need to perform operations on an object class.

1) Orders. Java

/*** Order * @ author zhengcy **/public class Orders implements Serializable {/*****/private static final long serialVersionUID = 1L; // IDprivate String id; // order number private String onumber; // Date private date Date; // customer name private String cname; // order private List <Item> items; public String getId () {return id;} public void setId (String id) {this. id = id;} public Date getDate () {return date;} public void setDate (Date date) {this. date = date;} public String getCname () {return cname;} public void setCname (String cname) {this. cname = cname;} public String getOnumber () {return onumber;} public void setOnumber (String onumber) {this. onumber = onumber;} public List <Item> getItems () {return items;} public void setItems (List <Item> items) {this. items = items ;}}

2) Item. java
/*** Product order table ** @ author zhengcy **/public class Item {// quantity private Integer quantity; // unit price private Double price; // product code private String pnumber; public Integer getQuantity () {return quantity;} public void setQuantity (Integer quantity) {this. quantity = quantity;} public Double getPrice () {return price;} public void setPrice (Double price) {this. price = price;} public String getPnumber () {return pnumber;} public void setPnumber (String pnumber) {this. pnumber = pnumber ;}}


Step 3: implement the OrdersDao class, that is, implement the Orders database operation interface. This OrdersDao also inherits the MongoBase interface. Here, OrdersDao does not implement other interfaces.

/*** Order Dao * @ author zhengcy **/public interface OrdersDao extends MongoBase <Orders> {}

Step 4: implement the specific class of OrdersDaoImpl, which is the actual operation of the database.

/*** Order implementation ** @ author zhengcy **/@ Repository ("ordersDao") public class OrdersDaoImpl implements OrdersDao {@ Resourceprivate your template into template; @ Overridepublic void insert (Orders object, string collectionName) {template. insert (object, collectionName) ;}@ Overridepublic void save (Orders object, String collectionName) {rule template. save (object, collectionName) ;}@ Overridepublic void insertAll (List <Orders> objects) {custom template. insertAll (objects );}}

(2) Implement the test class. We will test it.

In order to save time, we did not write the service class. We can call dao directly to implement the TestOrders. java class.

/*** Test order ** @ author zhengcy **/public class TestOrders {private static OrdersDao ordersDao; private static ClassPathXmlApplicationContext app; private static String collectionName; @ BeforeClass public static void initSpring () {try {app = new ClassPathXmlApplicationContext (new String [] {"classpath: applicationContext-mongo.xml", "classpath: spring-dispatcher.xml"}); ordersDao = (OrdersDao) app. getBean ("ordersDao"); collectionName = "orders";} catch (Exception e) {e. printStackTrace () ;}// add @ Test public void testSave () throws ParseException {}// add @ Test public void testInsert () to Test the Insert method () throws ParseException {}// add @ Test public void testInsertAll () throws ParseException to Test InsertAll {}}

1) Test the Save method to add

// Add @ Test public void testSave () throws ParseException {SimpleDateFormat form = new SimpleDateFormat ("yyyy-mm-dd") to Test the Save method "); // order Orders order = new Orders (); order. setOnumber ("001"); order. setDate (form. parse ("2015-07-25"); order. setCname ("zcy"); // order details List <Item> items = new ArrayList <Item> (); Item item1 = new Item (); item1.setPnumber ("p001 "); item1.setPrice (4.0); item1.setQuantity (5); items. add (item1); Item item2 = new Item (); item2.setPnumber ("p002"); item2.setPrice (8.0); item2.setQuantity (6); items. add (item2); order. setItems (items); ordersDao. insert (order, collectionName );}

When we query MongoDB, the Order details document is embedded, indicating that we have successfully added the document.

Add the test Insert method. This is not detailed here, just like the Save method.

2) Test the InsertALL method to add

// Add @ Test public void testInsertAll () throws ParseException {List <Orders> orders = new ArrayList <Orders> (); for (int I = 1; I <= 10; I ++) {SimpleDateFormat form = new SimpleDateFormat ("yyyy-mm-dd"); // order Orders order = new Orders (); order. setOnumber ("00" + I); order. setDate (form. parse ("2015-07-25"); order. setCname ("zcy" + I); // List of Order details <Item> items = new ArrayList <Item> (); Item item1 = new Item (); item1.setPnumber ("p00" + I); item1.setPrice (4.0 + I); item1.setQuantity (5 + I); items. add (item1); Item item2 = new Item (); item2.setPnumber ("p00" + (I + 1); item2.setPrice (8.0 + I); item2.setQuantity (6 + I ); items. add (item2); order. setItems (items); orders. add (order);} ordersDao. insertAll (orders) ;}< span style = "font-family: Arial, Helvetica, sans-serif; background-color: rgb (255,255,255);" ></span>

We added 10 documents with order details embedded in batch. When we query MongoDB, we found the data, which indicates that we inserted the data successfully.


> db.orders.find()  { "_id" : ObjectId("55b387ebee10f907f1c9d461"), "_class" : "com.mongo.model.Orders", "onumber" : "001", "date" : ISODate("2015-01-24T16:07:00Z"), "cname"        : "zcy1", "items" : [ { "quantity" : 6, "price" : 5, "pnumber" : "p001" }, { "quantity" : 7, "price" : 9, "pnumber" : "p002" } ] }  { "_id" : ObjectId("55b387ebee10f907f1c9d462"), "_class" : "com.mongo.model.Orders", "onumber" : "002", "date" : ISODate("2015-01-24T16:07:00Z"), "cname"        : "zcy2", "items" : [ { "quantity" : 7, "price" : 6, "pnumber" : "p002" }, { "quantity" : 8, "price" : 10, "pnumber" : "p003" } ] } { "_id" : ObjectId("55b387ebee10f907f1c9d463"), "_class" : "com.mongo.model.Orders", "onumber" : "003", "date" : ISODate("2015-01-24T16:07:00Z"), "cname" :      "zcy3", "items" : [ { "quantity" : 8, "price" : 7, "pnumber" : "p003" }, { "quantity" : 9, "price" : 11, "pnumber" : "p004" } ] }{ "_id" : ObjectId("55b387ebee10f907f1c9d464"), "_class" : "com.mongo.model.Orders", "onumber" : "004", "date" : ISODate("2015-01-24T16:07:00Z"), "cname" :       "zcy4", "items" : [ { "quantity" : 9, "price" : 8, "pnumber" : "p004" }, { "quantity" : 10, "price" : 12, "pnumber" : "p005" } ] }{ "_id" : ObjectId("55b387ebee10f907f1c9d465"), "_class" : "com.mongo.model.Orders", "onumber" : "005", "date" : ISODate("2015-01-24T16:07:00Z"), "cname" :       "zcy5", "items" : [ { "quantity" : 10, "price" : 9, "pnumber" : "p005" }, { "quantity" : 11, "price" : 13, "pnumber" : "p006" } ] }...........>

3) If we use Save and Insert for the same _ ID, what we described earlier? Let's test it.

When we add a document without setting the _ ID attribute value, when the document is added to MongoDB, an index and uniqueness are automatically generated for the ID attribute/field of objectID. If we specify the value of _ ID, the speed will be slow, because _ ID is indexed by default.

   > db.orders.find()    { "_id" : "1", "_class" : "com.mongo.model.Orders", "onumber" : "001", "date" :ISODate("2015-01-24T16:07:00Z"), "cname" : "zcy1", "items" : [ { "quantit       y" : 5,"price" : 4, "pnumber" : "p001" }, { "quantity" : 6, "price" : 8, "pnumber" : "p002" } ] }

The ObjectId value "_ id": "1" already exists. When we add a document to the Save and Insert methods respectively, specify that "_ id": "1" already exists ".


1. Test the Insert method to add

// Add @ Test public void testInsert () throws ParseException {SimpleDateFormat form = new SimpleDateFormat ("yyyy-mm-dd") to Test the Insert method "); // order Orders order = new Orders (); order. setId ("1"); order. setOnumber ("002"); order. setDate (form. parse ("2015-07-25"); order. setCname ("zcy2"); // order details List <Item> items = new ArrayList <Item> (); Item item1 = new Item (); item1.setPnumber ("p003 "); item1.setPrice (4.0); item1.setQuantity (5); items. add (item1); Item item2 = new Item (); item2.setPnumber ("p003"); item2.setPrice (8.0); item2.setQuantity (6); items. add (item2); order. setItems (items); ordersDao. insert (order, collectionName );}

When we add the same ID, an error occurs when adding the document.

Org. springframework. dao. duplicateKeyException: insertDocument: caused by ::: 11000 E11000 duplicate key error index: test. orders. $ _ id _ dup key: {: "1"}; nested exception is com. mongodb. except exception $ DuplicateKey: insertDocument: caused by: 11000 E11000 duplicate key error index: test. orders. $ _ id _ dup key: {: "1 "}

When the persistent layer class is called to save domain updates, the primary key or uniqueness constraint conflict.

2. Test the Save method.

// Add @ Test public void testSave () throws ParseException {SimpleDateFormat form = new SimpleDateFormat ("yyyy-mm-dd") to Test the Save method "); // order Orders order = new Orders (); order. setId ("1"); order. setOnumber ("002"); order. setDate (form. parse ("2015-07-25"); order. setCname ("zcy2"); // order details List <Item> items = new ArrayList <Item> (); Item item1 = new Item (); item1.setPnumber ("p003 "); item1.setPrice (4.0); item1.setQuantity (5); items. add (item1); Item item2 = new Item (); item2.setPnumber ("p003"); item2.setPrice (8.0); item2.setQuantity (6); items. add (item2); order. setItems (items); ordersDao. save (order, collectionName );}

When we add the same ID, if it already exists, we will update the corresponding document and call update to update the document.

  > db.orders.find()     { "_id" : "1", "_class" :"com.mongo.model.Orders", "onumber" : "002","date" :ISODate("2015-01-24T16:07:00Z"),"cname" : "zcy2", "items" : [ {"quantity"        : 5,"price": 4, "pnumber" : "p003" }, { "quantity" : 6,"price" : 8, "pnumber" : "p003" } ] }

Note:

(1) save: When we add a document, if there is a document with the same _ ID, it will overwrite the original one.

(2) insert: when adding a document, if there is an identical _ ID, the addition will fail.

(3) MongoDB provides insertAll for batch addition. you can insert a list at a time, which is more efficient. To save data, you need to insert documents one by one, which is less efficient.
3. delete documents and collections

 

1. delete a document

 

Spring Data MongoDB's release template provides the following methods to delete documents:

1) We will focus on deleting documents based on conditions.

Step 1: We added an interface for deleting documents based on conditions in the basic interface MongoBase. java class.

// Delete public void remove (String field, String value, String collectionName) according to the conditions );

Step 2: add an implementation method to the OrdersDaoImpl class to delete the document according to the conditions.

         @Overridepublic void remove(Map<String, Object> params,String collectionName) {mongoTemplate.remove(new Query(Criteria.where("id").is(params.get("id"))),User.class,collectionName);}

> db.orders.find(){ "_id" : "1", "_class" : "com.mongo.model.Orders", "onumber" : "001", "date" :ISODate("2015-01-24T16:07:00Z"), "cname" : "zcy1", "items" : [ { "quantity" :   5,"price" : 4, "pnumber" : "p001" }, { "quantity" : 6, "price" : 8, "pnumber" : "p002" } ] }{ "_id" : "2", "_class" : "com.mongo.model.Orders", "onumber" : "002", "date" :ISODate("2015-01-24T16:07:00Z"), "cname" : "zcy2", "items" : [ { "quantity" :   5,"price" : 4, "pnumber" : "p003" }, { "quantity" : 6, "price" : 8, "pnumber" : "p004" } ] }>

Two documents are available for querying MongoDB.

2) implementation test class

        @Test public void testRemove() throws ParseException{ordersDao.remove("onumber","002", collectionName);}

We delete the document according to the onumber = 002 Condition

    > db.orders.find()      { "_id" : "1", "_class" : "com.mongo.model.Orders", "onumber" : "001", "date" :ISODate("2015-01-24T16:07:00Z"), "cname" : "zcy1", "items" : [ { "quantity" :  5,"price" : 4, "pnumber" : "p001" }, { "quantity" : 6, "price" : 8, "pnumber" : "p002" } ] }

Only documents with onumber = 001 are left.

Delete the orders data, the Set still exists, and the index still exists, which is equivalent to the SQL truncate command.


2. delete a set

 

Step 1: We added an interface to the basic interface MongoBase. java class to delete a set based on conditions.

// Delete the public void dropCollection (String collectionName );

Step 2: add an implementation method to the OrdersDaoImpl class to delete a set based on conditions.

         @Overridepublic void dropCollection(String collectionName) {mongoTemplate.dropCollection(collectionName);}

The Set and index do not exist, and the type of SQL is drop.









Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.