利用Spring Data MongoDB持久化文檔數(shù)據(jù)的方法教程
前言
本文主要給大家介紹了關于利用Spring Data MongoDB持久化文檔數(shù)據(jù)的相關內(nèi)容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。
介紹
- NoSQL:not only SQL,非關系型數(shù)據(jù)
- MongoDB是文檔型數(shù)據(jù),文檔是獨立的實體,文檔數(shù)據(jù)庫不適用于關聯(lián)關系明顯的數(shù)據(jù)
Spring Data MongoDB
1.Spring Data MongoDB提供了三種方式在Spring應用中使用MongoDB
- 通過注解實現(xiàn)對象-文檔映射
- 使用MongoTemplate實現(xiàn)基于模板的數(shù)據(jù)庫訪問
- 自動化的運行時Repository生成功能
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;
/**
* Spring Data MongoDB注解將Java類型映射為文檔
*/
@Document //這是一個文檔
public class Order {
@Id //指定id
private String id;
@Field("client") //覆蓋默認的域名
private String customer;
private String type;
private Collection<Item> items = new LinkedHashSet<>();
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;
}
}
2.啟用MongoDB
- 通過@EnableJpaRepositories注解啟用Spring Data的自動化JPA Repository生成功能
- @EnableMongoRepositories為MongoDB實現(xiàn)了相同的功能
第一種方式:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.MongoClient;
/**
*
* Spring Data MongoDB的配置
*
*/
@Configuration
@EnableMongoRepositories(basePackages="com.adagio.db") //啟用MongoDB的Repository功能
public class MongoConfig {
/**
* MongoTemplate Bean
* @param mongoDbFactory
* @return
*/
@Bean
public MongoOperations mongoTemplate(){
return new MongoTemplate(mongoDbFactory());
}
/**
* MongoDbFactory bean
* @return
*/
public MongoDbFactory mongoDbFactory(){
return new SimpleMongoDbFactory(mongoClient(), "com.adagio.db");
}
/**
* MongoClient bean
* @return
*/
public MongoClient mongoClient(){
return new MongoClient("localhost");
}
}
第二種方式
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
/**
*
* Spring Data MongoDB的配置
* 擴展AbstractMongoConfiguration
*
*/
@Configuration
@EnableMongoRepositories(basePackages="com.adagio.db") //啟用MongoDB的Repository功能
public class MongoConfig2 extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return "OrdersDB"; //指定數(shù)據(jù)庫名
}
@Autowired
private Environment env;
@Override
public Mongo mongo() throws Exception {
// return new MongoClient(); //創(chuàng)建Mongo客戶端
//如果MongoDB服務器運行在其他的機器上
// return new MongoClient("mongoServer");
//如果MongoDB服務器監(jiān)聽的端口不是默認端口27017
// return new MongoClient("mongoServer", 37017);
//如果MongoDB服務器在生產(chǎn)配置上,啟用了認證功能
MongoCredential credential = MongoCredential.createCredential(
env.getProperty("mongo.username") , "OrdersDB",
env.getProperty("mongo.password").toCharArray());
return new MongoClient(
new ServerAddress("localhost", 37017),
Arrays.asList(credential));
}
}
3.為模型添加注解,實現(xiàn)MongoDB持久化
- 用于對象-文檔映射的Spring Data MongoDB注解
@Document 標示映射到MongoDB文檔上的領域對象 類似JPA @Entity注解
@Id 標示某個域為ID域
@DbRef 標示某個域要引用的其它的文檔,這個文檔有可能位于另一個數(shù)據(jù)庫中
@Field 為文檔域指定自定義的元數(shù)據(jù)
@Version 標示某個屬性用作版域 - 注意:沒有添加注解的屬性,也會持久化為文檔中域,除非設置瞬時態(tài)(transient)
- 注意:
Order.items屬性,不是 關聯(lián)關系,會完全嵌入到Order中
4.使用MongoTemplate訪問MongoDB
- 配置類中配置的MongoTemplate bean,將其注入到使用的地方
- @Autowired MongoOperations mongo;
- MongoOperations是MongoTemplate所實現(xiàn)的接口
- void save(Object objectToSave, String collectionName);
- save第一個參數(shù)是新創(chuàng)建的對象,第二個參數(shù)是要保存的文檔存儲的名稱
5.編寫MongoDB Repository
- 使用Spring Data MongoDB來創(chuàng)建Repository
- 通過@EnableMongoRepositories注解啟用Spring Data MongoDB的Repository功能
- 通過擴展MongoRepository接口,能夠繼承多個CRUD操作
6.查詢方式:
- 自定義查詢
- 指定查詢
- 混合定義查詢
//自定義查詢
List<Order> findByCustomer(String customer);
List<Order> getByCustomer(String customer);
List<Order> readByCustomer(String customer);
int countByCustomer(String customer);
List<Order> findByCustomerLike(String customer);
List<Order> findByCustomerAndType(String customer, String type);
List<Order> getByType(String type);
//指定查詢
@Query("{customer:'Chuck Wagon'}")
List<Order> findChucksOrders();
混合自定義的功能
1.首先,定義中間接口
import java.util.List;
public interface OrderOperations {
List<Order> findOrderByType(String t);
}
2.編寫混合實現(xiàn)
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;
public class OrderOperationsimpl implements OrderOperations {
@Autowired
private MongoOperations mongo; //注入MongoOperations
@Override
public List<Order> findOrderByType(String t) {
String type = t.equals("NET") ? "WEB" : t;
//創(chuàng)建查詢
Criteria where = Criteria.where("type").is(type);
Query query = Query.query(where);
//執(zhí)行查詢
return mongo.find(query, Order.class);
}
}
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
String在棧中,StringBuffer在堆中!所以String是不可變的,數(shù)據(jù)是共享的。StringBuffer都是獨占的,是可變的(因為每次都是創(chuàng)建新的對象?。?/div> 2015-11-11
SpringBoot Actuator未授權訪問漏洞解決方案
工作的時候遇到過提示Spring Boot后端存在Actuator未授權訪問漏洞,網(wǎng)上有很多詳細的解釋文章,在這里做一個簡單的總結、介紹和分享,需要的朋友可以參考下2023-09-09
深入了解Java中Cookie和Session的區(qū)別
會話跟蹤是Web程序中常用的技術,用來跟蹤用戶的整個會話,常用的會話跟蹤技術是Cookie與Session,本文就詳細的介紹一下Java中Cookie和Session的區(qū)別,感興趣的可以了解一下2023-06-06
java自定義注解實現(xiàn)前后臺參數(shù)校驗的實例
下面小編就為大家?guī)硪黄猨ava自定義注解實現(xiàn)前后臺參數(shù)校驗的實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11
解決Android Studio安裝后運行出錯dose not...和Internal error...
這篇文章主要介紹了解決Android Studio安裝后運行出錯dose not...和Internal error...的相關資料,需要的朋友可以參考下2017-03-03最新評論

