Spring Boot整合MongoDB实现增删改查

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenwill3/article/details/79048090

MongoDB这两年来是本人一直使用较多的,之前的使用大多通过封装的工具类对数据库进行操作,虽然也算稳定,但有了Spring Boot之前的工具类直接加到SpringBoot里就没那么好使了,因此查阅资料后自己小试牛刀写了个增删改查,觉得也还不错,所以分享给大家看看

1 pom和主配置文件,为了方便大家复制粘贴贴个完整的

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.debug</groupId>
  <artifactId>usemongo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>usemongo</name>
  <url>http://maven.apache.org</url>

   <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
  </properties>
  
  <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.4.5.RELEASE</version>
  </parent>
  
  <dependencies>
    <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-mongodb</artifactId>
	</dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
           <scope>true</scope>
   </dependency>
    <dependency>
	    <groupId>com.alibaba</groupId>
	    <artifactId>fastjson</artifactId>
	    <version>1.2.38</version>
   </dependency>
   <dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-freemarker</artifactId>
  </dependency>
   
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  
  <build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
			<configuration>
				<!--fork :  如果没有该项配置,devtools不会起作用,即应用不会restart -->
				<fork>true</fork>
			</configuration>
		</plugin>
	</plugins>
 </build>
</project>
有几个配置大家根据喜好选择例如freemarker等,不要可根据需要去掉

spring.data.mongodb.database=test
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.username=test
spring.data.mongodb.password=654321
配置文件只写了MongoDB的一些简单配置,只作为参考,不一定要这样写

2 实体类/pojo

package com.debug.pojo;

import org.springframework.data.annotation.Id;

public class Order {
	
	@Id
	private int id;
	private String orderNo;
	private String nickName;
	private double totalPrice;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getOrderNo() {
		return orderNo;
	}

	public void setOrderNo(String orderNo) {
		this.orderNo = orderNo;
	}

	public String getNickName() {
		return nickName;
	}

	public void setNickName(String nickName) {
		this.nickName = nickName;
	}

	public double getTotalPrice() {
		return totalPrice;
	}

	public void setTotalPrice(double totalPrice) {
		this.totalPrice = totalPrice;
	}

}
第一个属性id可要可不要,MongoDB建议使用自带的_id作为主键,这样不会重复;另外如果实体和表名不一致可以使用
@Document注解指定,使用方法如下:

@Document(collection="orderInfo")

如果属性和数据库字段不同可以使用@Field("字段名")  指定

3  dao或repository(原理和Spring data jpa相似)

package com.debug.repository;

import java.util.regex.Pattern;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.repository.MongoRepository;

import com.debug.pojo.Order;

public interface OrderRepository extends MongoRepository<Order, Integer>{
   Order getByOrderNo(String orderNo);
   public Order getByOrderNoLike(String orderNo);
}
Spring data jpa的那一套查询规则,在MongoDB仍然适用

4 service层

package com.debug.service;

import com.debug.pojo.Order;

public interface OrderService {
	public Order getByOrderNo(String orderNo);
	public Order getByOrderNoLike(String orderNo);
	public void saveOrder(Order order);
	public void removeOrderByOrderNo(String orderNo);
	public void updateOrder(Order order);
}
package com.debug.service.impl;

import javax.annotation.Resource;
import javax.annotation.Resources;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.debug.pojo.Order;
import com.debug.repository.OrderRepository;
import com.debug.service.OrderService;

@Service
public class OrderServiceImpl implements OrderService{
	
	@Resource
	private MongoTemplate mongoTemplate;

	@Resource
	private OrderRepository orderRepository;
	
	public Order getByOrderNo(String orderNo) {
		
		return orderRepository.getByOrderNo(orderNo);
	}

	
	public void saveOrder(Order order) {
		orderRepository.save(order);
		
	}
	
    public Order getByOrderNoLike(String orderNo) {
		
		return orderRepository.getByOrderNoLike(orderNo);
	}
    
    public void removeOrderByOrderNo(String orderNo) {
    	Query q=new Query(new Criteria("orderNo").is(orderNo));
    	mongoTemplate.remove(q,Order.class);
    }
    
    public void updateOrder(Order order) {
    	Query q=new Query(new Criteria("orderNo").is(order.getOrderNo()));
    	Update update=new Update().set("nickName", order.getNickName());
    	mongoTemplate.updateMulti(q, update, Order.class);
    }

}
这里使用了MongoDBTempalte作删除和修改操作,查询使用的是spring data mongodb

5  controller的代码

package com.debug.controller;

import java.util.UUID;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.debug.pojo.Order;
import com.debug.repository.OrderRepository;
import com.debug.service.OrderService;

@RestController
public class OrderController {
	
	@Resource
	private OrderService orderService;

	@RequestMapping("/saveOrder")
	@ResponseBody
	public String saveOrder() {
		
		Order order=new Order();
		order.setId(2);
		order.setNickName("潘玮柏");
		order.setOrderNo("X797468");
		order.setTotalPrice(4500.00);
		
		orderService.saveOrder(order);
		
		return "OK";
	}
	
	@RequestMapping("/getOrderByOrderNo")
	@ResponseBody
	public Order getOrderByOrderNo() {
		Order order=orderService.getByOrderNo("X797466");
		return order;
	}
	
	@RequestMapping("/getOrderByOrderNoLike")
	@ResponseBody
	public Order getOrderByOrderNoLike() {
		//String cond="X797";
		//Pattern pattern=Pattern.compile("^.*"++".*$");            
		Order order=orderService.getByOrderNoLike("X797");
		return order;
	}
	
	@RequestMapping("/removeOrderByOrderNo")
	@ResponseBody
	public String removeOrderByOrderNo() {         
		orderService.removeOrderByOrderNo("X797468");
		return "OK";
	}
	
	@RequestMapping("/updateOrder")
	@ResponseBody
	public String updateOrder() {    
		Order order=new Order();
		order.setNickName("Justin Timberlake");
		order.setOrderNo("X797467");
		orderService.updateOrder(order);
		return "OK";
	}
}
OK全部搞定,收工大笑

展开阅读全文

没有更多推荐了,返回首页