Spring-data對MongoDB進行了很好的支持,接下來就講解一下關於Spring對MongoDB的配置和一些正常的使用java
我下面的工程使用的是Spring的Java配置的方式和Maven構建git
具體的工程代碼你們能夠訪問個人Github地址:https://github.com/zoeminghong/springmvc-javaconfiggithub
package springmvc.rootconfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.MongoClientFactoryBean; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import com.mongodb.Mongo; @Configuration // 啓用MongoDB的Repository功能,會對其Repositories自動掃描 @EnableMongoRepositories(basePackages = "springmvc.orders.db") public class MongoConfig { // MongoClient配置 @Bean public MongoClientFactoryBean mongo() { MongoClientFactoryBean mongo = new MongoClientFactoryBean(); mongo.setHost("localhost"); //MongoCredential credential=MongoCredential.createCredential(env.getProperty("mongo.username"), "OrdersDB",env.getProperty("mongo.password").toCharArray()); // mongo.setCredentials(new MongoCredential[]{credential}); //還能夠對端口進行配置 return mongo; } // Mongo Template配置 @Bean public MongoOperations mongoTemplate(Mongo mongo) { //OrdersDB就是Mongo的數據庫 return new MongoTemplate(mongo, "OrdersDB"); } }
爲了訪問數據庫的時候,咱們可能還須要賬號密碼web
MongoCredential credential=MongoCredential.createCredential(env.getProperty("mongo.username"), "OrdersDB",env.getProperty("mongo.password").toCharArray()); mongo.setCredentials(new MongoCredential[]{credential});
package springmvc.bean; import java.util.Collection; import java.util.LinkedHashSet; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; //這是文檔 @Document public class Order { //指定ID @Id private String id; //爲域重命名 @Field("client") private String customer; private String type; private Collection<Item> items=new LinkedHashSet<Item>(); public String getId() { return id; } public void setId(String id) { this.id = id; } 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<Item> getItems() { return items; } public void setItems(Collection<Item> items) { this.items = items; } }
package springmvc.bean; 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; } }
註解 | 描述 |
---|---|
@Document | 標示映射到mongoDB文檔上的領域對象 |
@ID | 標示某個爲ID域 |
@DbRef | 標示某個域要引用其餘的文檔,這個文檔有可能位於另一個數據庫中 |
@Field | 爲文檔域指定自定義的元數據 |
@Version | 標示某個屬性用做版本域 |
若不使用@Field註解,域名就與Java屬性相同spring
上面之因此Item的Java類爲何沒有@Document註解,是由於咱們不會單獨想Item持久化爲文檔mongodb
package springmvc.web; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import springmvc.bean.Order; import springmvc.orders.db.OrderRepository; @Controller public class HomeController { @Autowired MongoOperations mongo; @RequestMapping(value = { "/", "index" }, method = RequestMethod.GET) public String index() { long orderCount=mongo.getCollection("order").count(); System.out.println(orderCount); // Order order = new Order(); // order.setId("1"); // order.setCustomer("gg"); // order.setType("2"); //第二個參數是文檔存儲的名稱 // mongo.save(order,"order"); // String orderId="1"; // Order order=mongo.findById(orderId, Order.class); // System.out.println(order.getCustomer()); return "index"; } }
在這裏咱們將MongoTemplate注入到一個類型爲MongoOperations的屬性中。MongoOperations是MongoTemplate所實現的接口,MongoOperations中存在不少文檔操做方法數據庫
MongoOperations其實已經能知足不少需求了微信
若是尚未知足你的需求,接下來我就介紹一下,如何編寫MongoDB Repositorymvc
package springmvc.orders.db; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import springmvc.bean.Order; public interface OrderRepository extends MongoRepository<Order, String> { List<Order> findByCustomer(String c); List<Order> findByCustomerLike(String c); List<Order> findByCustomerAndType(String c, String t); List<Order> findByCustomerLikeAndType(String c, String t); }
看到這裏,你們有沒有發現package的地址就是咱們剛纔@EnableMongoRepositories(basePackages = "springmvc.orders.db")的配置app
MongoRepository接口有兩個參數,第一個是帶有@Document註解的對象類型,也就是該Repository要處理的類型。第二個參數是帶有@Id註解的屬性類型
OrderRepository繼承了MongoRepository中不少自帶的方法
方法 | 描述 |
---|---|
long count() | 返回指定Repository類型的文檔數量 |
void delete(Iterable<? extends T>) | 刪除與指定對象關聯的全部文檔 |
void delete(T) | 刪除與指定對象關聯的文檔 |
void delete(ID) | 根據ID刪除某一個文檔 |
void deleteAll(); | 刪除指定Repository類型的全部文檔 |
boolean exists(Object) | 若是存在與指定對象相關聯的文檔,則返回true |
boolean exists(ID) | 若是存在與指定對象相關聯的文檔,則返回true |
List<T>findAll() | 返回指定Repository類型的全部文檔 |
List<T>findAll(Iterable<ID>) | 返回指定文檔ID對應的全部文檔 |
List<T>findAll(Pageable) | 爲指定Repository類型,返回分頁且排序的文檔列表 |
List<T>findAll(Sort) | 爲指定Repository類型,返回排序後的全部文檔列表 |
T findOne(ID) | 爲指定的ID返回單個文檔 |
Save(terable<S>) | 保存指定Iterable中的全部文檔 |
save(<S>) | 爲給定的對象保存一條文檔 |
上面的咱們定義的四個方法都是咱們自定義的方法,其方法名存在不少意義,不能隨便定義
List<Order> findByCustomer(String c);
find爲查詢動詞,還能夠是read、get、count等
Customer爲斷言,判斷其行爲
在斷言中,會有一個或多個限制結果的條件。每一個條件必須引用一個屬性,而且還能夠指定一種比較操做。若是省略比較操做符的話,那麼這暗指是一種相等比較操做。不過,咱們也能夠選擇其餘的比較操做
類型 |
---|
IsAfter、After、IsGreaterThan、GreaterThan |
IsGreaterThanEqual、GreaterThanEqual |
IsBefore、Before、IsLessThan、LessThan |
IsLessThanEqual、LessThanEqual |
IsBetween、Between |
IsNull、Null |
IsNotNull、NotNull |
IsIn、In |
IsNotIn、NotIn |
IsStartingWith、StartingWith、StartsWith |
IsEndingWith、EndingWith、EndsWith |
IsContaining、Containing、Contains |
IsLike、Like |
IsNotLike、NotLike |
IsTure、True |
IsFalse、False |
Is、Equals |
IsNot、Not |
other
類型 |
---|
IgnoringCase、IgnoresCase、OrderBy、And、Or |
@Query("{'customer':'Chuck Wagon','type':?0}") List<Order> findChucksOrders(String t);
@Query中給定的JSON將會與全部的Order文檔進行匹配,並返回匹配的文檔,這裏的type屬性映射成「?0」,這代表type屬性應該與查詢方法的第0個參數相等,若是有多個參數,則"?1".....
package springmvc.orders.db; import java.util.List; import springmvc.bean.Order; public interface OrderOperations { List<Order> findOrdersByType(String t); }
package springmvc.orders.db; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import springmvc.bean.Order; public class OrderRepositoryImpl implements OrderOperations { @Autowired private MongoOperations mongo; //將混合實現注入MongoOperations @Override public List<Order> findOrdersByType(String t) { String type =t.equals("Net")?"2":t; Criteria where=Criteria.where("type").is(type); Query query=Query.query(where); return mongo.find(query, Order.class); } }
package springmvc.orders.db; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import springmvc.bean.Order; //繼承OrderOperations接口 public interface OrderRepository extends MongoRepository<Order, String>,OrderOperations { List<Order> findByCustomer(String c); List<Order> findByCustomerLike(String c); List<Order> findByCustomerAndType(String c, String t); List<Order> findByCustomerLikeAndType(String c, String t); @Query("{'customer':'Chuck Wagon','type':?0}") List<Order> findChucksOrders(String t); }
package springmvc.web; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import springmvc.bean.Order; import springmvc.orders.db.OrderRepository; @Controller public class HomeController { @Autowired MongoOperations mongo; @Autowired OrderRepository orderRepository; @RequestMapping(value = { "/", "index" }, method = RequestMethod.GET) public String index() { List<Order> list=orderRepository.findOrdersByType("2"); System.out.println(list.size()); return "index"; } }
以上這些關聯起來的關鍵點是OrderRepositoryImpl,這個名字前半部分與OrderRepository相同,只是添加了一個「Impl」後綴。若是想更改該後綴,能夠在MongoConfig類中更改成本身理想的後綴
@EnableMongoRepositories(basePackages = "springmvc.orders.db",repositoryImplementationPostfix="Stuff")
更多內容能夠關注微信公衆號,或者訪問AppZone網站