当前位置:Gxlcms > 数据库问题 > Spring Data MongoDB 二:添加、删除操作

Spring Data MongoDB 二:添加、删除操作

时间:2021-07-01 10:21:17 帮助过:9人阅读

   Spring  Data  MongoDB 项目提供与MongoDB文档数据库的集成,Spring与Hibernate集成时,Spring提供了org.springframework.orm.hibernate3.HibernateTemplate实现了对数据的CRUD操作, Spring Data  MongoDB提供了org.springframework.data.mongodb.core.MongoTemplate对MongoDB的CRUD的操作,包括对集成的对象映射文件和POJO之间的CRUD的操作。

   今天我们要介绍Java代码实现对MongoDB实现添加和删除操作。

二.添加

Spring  Data  MongoDB 的MongoTemplate提供了两种存储文档方式,分别是save和insert方法,这两种的区别:

  (1)save :我们在新增文档时,如果有一个相同_ID的文档时,会覆盖原来的。

  (2)insert:我们在新增文档时,如果有一个相同的_ID时,就会新增失败。

 

  1.接下来我们分别介绍的两种方式的具体语法。

 

(1)Save方式

        方法:

        1)void save (Object objectToSave) 保存文档到默认的集合。

        2)void save(Object objectToSave, String collectionName) 对指定的集合进行保存。

(2) Insert方式

     方法:

      1)void insert(Object objectToSave) 保存文档到默认的集合。

      2)void insertAll(Object objectsToSave) 批量添加到默认的集合。

      3)void insert(Object objectToSave, String collectionName) 对指定的集合进行保存。


 2. Spring实现MongoDB的添加操作

     我们在上一篇有介绍了,Spring Data MongoDB环境的搭建,这里不在具体介绍,我们直接实战。

    (1)介绍接口以及实现方法


       第一步:实现一个基础接口,是比较通用的 MongoBase.java类 

      public interface MongoBase<T> {
	// insert添加
	public void insert(T object,String collectionName); 
	// save添加
	public void save(T object,String collectionName); 
	//批量添加
	public void insertAll(List<T> object); 
      }
        

     第二步:我们实现文档的结构,也是实体类。

      我们这边有两个实体类,订单类(Orders.java)和对应订单详情类(Item.java),这里我们实现内嵌文档。如果没有内嵌文档的结构,只要对一个实体类的操作就OK。

         1)Orders.Java

/**
 * 订单
 * @author zhengcy
 *
 */
public class Orders implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//ID
	private String id;
	//订单号
	private String onumber;
	//日期
	private Date date;
	//客户名称
	private String cname;
	//订单
    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  
/**
 * 产品订购表
 * @author zhengcy
 *
 */
public class Item {
	
	//数量
	private Integer quantity;
	//单价
	private Double price;
	//产品编码
	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;
	}
}


       第三步:实现OrdersDao类,就是实现Orders自己操作数据库的接口,这个OrdersDao也继承了MongoBase接口,我们这边OrdersDao没实现其他额外的接口。

         
/**
 * 订单Dao
 * @author zhengcy
 *
 */
public interface OrdersDao extends MongoBase<Orders> {


}

  第四步:实现OrdersDaoImpl具体类,这边是实际操作数据库。

         

 /**
 * 订单实现
 * @author zhengcy
 *
 */
@Repository("ordersDao")
public class OrdersDaoImpl implements OrdersDao {
	@Resource
	private MongoTemplate mongoTemplate;

	@Override
	public void insert(Orders object, String collectionName) {
		mongoTemplate.insert(object, collectionName);
		
	}
	
	
	@Override
	public void save(Orders object, String collectionName) {
		mongoTemplate.save(object, collectionName);
		
	}
	
	@Override
	public void insertAll(List<Orders> objects) {
		mongoTemplate.insertAll(objects);
		
	}
}
    

(2)实现测试类,我们进行测试

      我们这边为了节省时间,就没写服务类,我们直接调用dao就可以了,实现了TestOrders.java类

        

/**
 * 测试订单
 * @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();
		}
         } 
	
	//测试Save方法添加
	@Test 
	public void testSave() throws ParseException
	{
		
	}
	//测试Insert方法添加
	@Test 
	public void testInsert() throws ParseException
	{
		
	}
	//测试InsertAll方法添加
	@Test 
	public void testInsertAll() throws ParseException
	{
		
	}
}
   

           

      1)测试Save方法添加

            
        //测试Save方法添加
	@Test 
	public void testSave() throws ParseException
	{
		 SimpleDateFormat form=new SimpleDateFormat("yyyy-mm-dd");
			//订单
		    Orders order =new Orders();
			order.setOnumber("001");
			order.setDate(form.parse("2015-07-25"));
			order.setCname("zcy");
			//订单详情
			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);
	}
          技术分享

        我们到MongoDB查询时,订单内嵌订单详情的文档,说明我们成功新增文档。

         测试Insert方法添加,这边就不在详情的介绍,跟Save方法一样。

       

        2)测试InsertALL方法添加

            

       //测试InsertAll方法添加
	@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");
			//订单
		    Orders order =new Orders();
			order.setOnumber("00"+i);
			order.setDate(form.parse("2015-07-25"));
			order.setCname("zcy"+i);
			//订单详情
			List<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>

        我们批量添加10条订单内嵌订单详情的文档,我们在MongoDB查询时,有查到数据,说明我们插入成功。


      
> 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)如果面对相同的_ID时,我们在使用Save和Insert时,会碰到我们前面介绍的那样?我们测试一下就知道了。

          我们在新增文档时,如果不设置_ID属性值,文档添加到MongoDB时,对于objectID的ID属性/字段自动生成一个字符串,带有索引和唯一性。如果我们指定_ID属性值时,速度会很慢,因为_ID默认是有索引的。

           
   > 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" } ] }
    

      ObjectId值"_id": "1"已经存在,我们分别对Save和Insert方法新增文档时,指定已经存在"_id": "1"。


        1.测试Insert方法添加

               

       //测试Insert方法添加
	@Test 
	public void testInsert() throws ParseException
	{
		 SimpleDateFormat form=new SimpleDateFormat("yyyy-mm-dd");
		    //订单
		    Orders order =new Orders();
		    order.setId("1");
			order.setOnumber("002");
			order.setDate(form.parse("2015-07-25"));
			order.setCname("zcy2");
			//订单详情
			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);
	}
   

        我们添加相同的ID时,执行添加文档时,添加出现错误

                 org.springframework.dao.DuplicateKeyException:insertDocument :: caused by :: 11000 E11000 duplicate key error index:test.orders.$_id_  dup key: { :"1" }; nested exception is com.mongodb.MongoException$DuplicateKey:insertDocument :: caused by :: 11000 E11000 duplicate key error index:test.orders.$_id_  dup key: { :"1" }

           

     调用持久层类的进行保存域更新的时候,主键或唯一性约束冲突。

       2.测试Save方法添加

          

       //测试Save方法添加	
	@Test 
	public void testSave() throws ParseException
	{
		 SimpleDateFormat form=new SimpleDateFormat("yyyy-mm-dd");
			//订单
		    Orders order =new Orders();
		    order.setId("1");
			order.setOnumber("002");
			order.setDate(form.parse("2015-07-25"));
			order.setCname("zcy2");
			//订单详情
			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);
	}
              

     我们添加相同的ID时,如果已经存在,会对相对应的文档进行更新,调用update更新里面的文档。

     

  > 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" } ] }

  说明:

    (1)save :我们在新增文档时,如果有一个相同_ID的文档时,会覆盖原来的。

    (2)insert:我们在新增文档时,如果有一个相同的_ID时,就会新增失败。

     (3)MongoDB提供了insertAll批量添加,可以一次性插入一个列表,效率比较高,save则需要一个一个的插入文档,效率比较低。
    

三、删除文档、删除集合

 

    1.      删除文档

 

                Spring  Data MongoDB 的MongoTemplate提供删除文档如下几个方法:

                技术分享

               1) 我们这边重点根据条件删除文档

                  第一步:我们在基础接口MongoBase.java类新增一个根据条件删除文档的接口  。    

             //根据条件删除
             public void remove(String field,String value,String collectionName);
               

              第二步:我们在OrdersDaoImpl类添加一个具体根据条件删除文档的实现方法。

                      
         @Override
	public 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" } ] }
>

   现在查询MongoDB有两条文档

       2)实现测试类

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

        我们根据onumber=002条件删除文档

    > 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" } ] }

        只剩下onumber=001的文档。

       删除orders的数据,集合还存在,索引都还存在,相当与SQ的truncate命令。


     2.      删除集合

 

                 第一步:我们在基础接口MongoBase.java类新增一个根据条件删除集合的接口。       

           //删除集合
            public void dropCollection(String collectionName);
                   

               第二步:我们在OrdersDaoImpl类添加一个具体根据条件删除集合的实现方法。

                            

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

                 集合、索引都不存在了,类型SQL的drop。

                 







版权声明:本文为博主原创文章,未经博主允许不得转载。

Spring Data MongoDB 二:添加、删除操作

标签:nosql   mongodb   spring   

人气教程排行