1. 程式人生 > >Spring註解配置Mongo及基本CRUD操作簡介

Spring註解配置Mongo及基本CRUD操作簡介

Mongo安裝配置參考基本操作等可參考http://www.runoob.com/mongodb/mongodb-tutorial.html,其中help()方法十分實用,可以不用讓使用者不用記太多方法,如help.collection.help()會顯示集合(相當於傳統資料庫中的的表)的所有方法,db.help()則顯示資料庫操作的所有方法。現在直接進主題:Mongo註解配置(對比XML配置真的十分十分簡便)。

POM新增以下依賴,測試前mongod.exe伺服器需處於開啟狀態:

<dependency>
  <groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId> <version>4.3.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.3.RELEASE</version> </dependency>
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.10.3.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId>
<version>4.12</version> </dependency>

POJO:

1.Order:

package per.nosql.pojo;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * Created by Wilson on 2017/5/5.
 */
@Document
public class Order {
    @Id
    private String id;
    private String customer;
    private String type;
    private Collection<Item> items = new LinkedHashSet<Item>();

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

    public void setCustomer(String customer) {
        this.customer = customer;
    }

    public void setType(String type) {
        this.type = type;
    }

    public void setItems(Collection<Item> items) {
        this.items = items;
    }

    public String getId() {
        return id;
    }

    public String getCustomer() {
        return customer;
    }

    public String getType() {
        return type;
    }

    public Collection<Item> getItems() {
        return items;
    }

    @Override
    public String toString() {
        return "Order{" +
                "id='" + id + '\'' +
                ", customer='" + customer + '\'' +
                ", type='" + type + '\'' +
                ", itemsSize=" + items.size() +
                '}';
    }
}
2.Item:

package per.nosql.pojo;

/**
 * Created by Wilson on 2017/5/5.
 */
public class Item {
    private Long id;
    private Order order;
    private String product;
    private double price;
    private int quantity;

    public Long getId() {
        return id;
    }

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

    public Order getOrder() {
        return order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }

    public String getProduct() {
        return product;
    }

    public void setProduct(String product) {
        this.product = product;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
}

Mongo配置類MongoConfig.class:

package per.nosql.config;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * Created by Wilson on 2017/5/5.
 */
@Configuration
@EnableMongoRepositories(basePackages = "per.nosql.dao")    //掃描指定包下的API,對比Mybatis的MapperScanner配置簡單很多
public class MongoConfig extends AbstractMongoConfiguration{

    /**
     * @return Mongo資料庫名,可通過開啟mongo.exe輸入show db檢視
     */
    @Override
    protected String getDatabaseName() {
        return "test";
    }

    /**
     * @return 返回MongoClient,構造方法可設定伺服器和埠號,預設伺服器為"127.0.0.1",埠為27017,詳情可看原始碼
     * @throws Exception
     */
    @Override
    public Mongo mongo() throws Exception {
        return new MongoClient();
    }
}
MongoTemplate已在AbstractMongoConfiguration中進行了初始化,若需更多的擴充套件配置可過載AbstractMongoConfiguration中的方法。

DAO介面:

package per.nosql.dao;

import org.springframework.data.mongodb.repository.MongoRepository;
import per.nosql.pojo.Order;

/**
 * Created by Wilson on 2017/5/5.
 */
public interface OrderRepository extends MongoRepository<Order,String>{
}
MongoRepository介面中已含基本的增刪改查操作,任何擴充套件Repository的介面將會在執行時自動生成實現

測試:

package per.nosql.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import per.nosql.config.MongoConfig;
import per.nosql.dao.OrderRepository;
import per.nosql.pojo.Item;
import per.nosql.pojo.Order;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;

/**
 * Created by Wilson on 2017/5/5.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class MongoTest {

    @Autowired
    OrderRepository orderRepository;

    @Test
    public void addOrder() {
        Order order = createOrder();
        orderRepository.insert(order);
        order.setType("second");
        orderRepository.insert(order);
        System.out.println(order);
//        assertEquals(1,orderRepository.count());
    }

    @Test
    public void updateOrder(){
        Order order = createOrder();
        order.setId("590c4172b81ff1d2f58665e7");
        order.setCustomer("Wilson");
        orderRepository.save(order);
    }

    @Test
    public void findAllOrders(){
        List<Order> orderList = orderRepository.findAll();
        StringBuffer buffer = new StringBuffer();
        orderList.forEach(each -> buffer.append(each).append("\n"));
        System.out.println(buffer.toString());
    }

    private Order createOrder(){
        Order order = new Order();
        order.setType("Test");
//        order.setCustomer("William");

        Item item1 = new Item();
        item1.setPrice(15);
        item1.setProduct("Java Mongo");
        item1.setQuantity(6);
      /*  Item item2 = new Item();
        item2.setPrice(13);
        item2.setProduct("Java Web");
        item2.setQuantity(3);*/
        order.setItems(Arrays.asList(item1));
        return order;
    }
}
save()方法既可進行插入資料,也可進行更新資料,更新時是若有屬性為null則對應的欄位都將更新為null,官方不推薦使用insert而推薦save進行資料插入,原始碼如下,主要是為了取代 避免特異性儲存API的使用

* Inserts the given entity. Assumes the instance to be new to be able to apply insertion optimizations. Use
* the returned instance for further operations as the save operation might have changed the entity instance
* completely. Prefer using {@link #save(Object)} instead to avoid the usage of store-specific API.
無論是insert還是save,執行成功後都會對實體進行ID回填,當再次進行save操作則是進行更新,更多的結果大家可自己操作獲得,具體測試結果就不截圖顯示了,如想新增其它的方法如條件查詢之類的請耐心等待下一篇。