MongoDB Spring 全注解整合实例

最近在学习mongoDB与Spring,学着用全注解的形式写了个mongoDB的小DEMO。下面附上源码

环境: IDEA,

            java1.6, 

            maven2.2


这是我整个工程的目录结构。

MongoDB Spring 全注解整合实例_第1张图片



我在源码里面做了详细的注解,所以博客里就不写了:

package com.jd.xiahongyun.config;

import com.mongodb.Mongo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoFactoryBean;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/*
* EnableMongoRepositories 启动MongoDB的 Repositories 功能
* basePackages 指定 Repositories  所在的包
* */
@Configuration
@EnableMongoRepositories(basePackages = "com.jd.xiahongyun.repositories")
public class MongoConfig {

    /**
     *创建mongo数据库实例:localhost指定数据库服务地址//也可以指定端口号,默认是27017
     */
    @Bean
    public MongoFactoryBean mongo(){
        MongoFactoryBean mongo = new MongoFactoryBean();
        mongo.setHost("localhost");
        return mongo;
    }

    /**
     *设置当前数据库名称为OrdersDB, MongoOperations的功能很强大
     *能够实现数据库的绝大部分操作, 但是没有用到他的功能
     */
    @Bean
    public MongoOperations mongoTemplate(Mongo mongo){
        return new MongoTemplate(mongo, "OrdersDB");
    }
}





package com.jd.xiahongyun.repositories;

import com.jd.xiahongyun.model.Order;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

import java.util.List;

/**
 * 查看MongoRepository的源代码 会发现其最底层实现了Repository接口,所以
 * OrderRepository会传递性的扩展Repository接口。我们知道,任何扩展Repository
 * 的接口将会在运行时自动由Spring data 帮助我们进行实现,所以下列方法会由
 * Spring Data 根据方法名字进行实现
 *             find  By  Customer   findd 查询动词  by  Customer 参数断言
 * 不懂得同学可以学习Spring Data 实现方法的规则
 *
 */
public interface OrderRepository extends MongoRepository {

    List findByCustomer(String c);

    List findByCustomerLike(String c);

    List findByCustomerAndType(String c, String t);

    List getByType(String type);

    @Query("{customer:'Chuck Wagon'}")
    List findChucksOrders();
}

package com.jd.xiahongyun.model;

public class Item {

    private Long id;
    private Order order;
    private String product;
    private double price;
    private int quantity;

    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;
    }

    public Long getId() {
        return id;
    }

    public Order getOrder() {
        return order;
    }
}

package com.jd.xiahongyun.model;

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;

@Document
public class Order {

    @Id
    private String id;
    @Field("customer")
    private String customer;
    private String type;
    private Collection items = new LinkedHashSet();

    public String getCustomer() {
        return customer;
    }

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

    public String getType() {
        return type;
    }

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

    public Collection getItems() {
        return items;
    }

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

    public String getId() {
        return id;
    }
}

import com.jd.xiahongyun.config.MongoConfig;
import com.jd.xiahongyun.model.Item;
import com.jd.xiahongyun.model.Order;
import com.jd.xiahongyun.repositories.OrderRepository;
import com.sun.org.apache.xpath.internal.SourceTree;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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

import static org.junit.Assert.assertEquals;

@ContextConfiguration(classes = MongoConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class MongoDbTest {

	@Autowired
	private OrderRepository orderRepository;

	
	@Autowired
    MongoOperations mongoOps;
	
	@Before
	public void cleanup() {
		// Deleting all orders (just in case something is left over from a previous failed run)
		orderRepository.deleteAll();
	}
	
	@Test
	public void testMongoRepository() {
		Order order = createAnOrder();
		
		// Saving an order
		Order savedOrder = orderRepository.save(order);		

		
		// Finding an order by ID
		Order foundOrder = orderRepository.findOne(savedOrder.getId());
		System.out.println(foundOrder.getId());
		System.out.println(foundOrder.getCustomer());
		System.out.println(foundOrder.getType());
		Set items = (Set) foundOrder.getItems();
		for(Item item: items){
			System.out.println(item.getProduct());
		}

		// Finding an order by a single field value
		List chucksOrders = orderRepository.findByCustomer("Chuck Wagon");

		// Finding an order by a single field value like
		List chuckLikeOrders = orderRepository.findByCustomerLike("Chuck");


		// Finding an order by multiple field values
		List chucksWebOrders = orderRepository.findByCustomerAndType("Chuck Wagon", "WEB");

		List chucksPhoneOrders = orderRepository.findByCustomerAndType("Chuck Wagon", "PHONE");

		// Finding an order by a custom query method
		List chucksOrders2 = orderRepository.findChucksOrders();

		
		
		// Deleting an order
		orderRepository.delete(savedOrder.getId());

	}

	private Order createAnOrder() {
		Order order = new Order();
		order.setCustomer("Chuck Wagon");
		order.setType("WEB");
		Item item1 = new Item();
		item1.setProduct("Spring in Action");
		item1.setQuantity(2);
		item1.setPrice(29.99);
		Item item2 = new Item();
		item2.setProduct("Module Java");
		item2.setQuantity(31);
		item2.setPrice(29.95);
		order.setItems(Arrays.asList(item1, item2));
		return order;
	}
	
}









你可能感兴趣的:(MongoDB Spring 全注解整合实例)