版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z28126308/article/details/71216143
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操作则是进行更新,更多的结果大家可自己操作获得,具体测试结果就不截图显示了,如想添加其它的方法如条件查询之类的请耐心等待下一篇。