【MongoDB】spring-data-mongo配置

來源:互聯網
上載者:User

標籤:spring-data-mongo   mongodb   

  • config.properties

#mongodb settingmongo.host=127.0.0.1mongo.port=27017mongo.connectionsPerHost=100mongo.threadsAllowedToBlockForConnectionMultiplier=50mongo.connectTimeout=1000mongo.maxWaitTime=1500mongo.autoConnectRetry=truemongo.socketKeepAlive=truemongo.socketTimeout=0mongo.slaveOk=true


  • spring_mongo.xml

<!--引入配置屬性檔案 --><context:property-placeholder location="classpath:db.properties" /><!-- mongodb配置 --><mongo:mongo id="mongo" replica-set="${mongo.replica-set}" write-concern="SAFE"><mongo:options connections-per-host="${mongo.connectionsPerHost}"threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}"auto-connect-retry="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}"socket-timeout="${mongo.socketTimeout}" slave-ok="${mongo.slaveOk}"write-number="1" write-timeout="0" write-fsync="true" /></mongo:mongo><!-- mongo的工廠,通過它來取得mongo執行個體,dbname為mongodb的資料庫名,沒有的話會自動建立 --><mongo:db-factory id="mongoDbFactory" dbname="uba" mongo-ref="mongo" /><!-- 讀寫分離層級配置  --><!-- 首選主節點,大多情況下讀操作在主節點,如果主節點不可用,如容錯移轉,讀操作在從節點。 --><bean id="primaryPreferredReadPreference" class="com.mongodb.TaggableReadPreference.PrimaryPreferredReadPreference"></bean><!-- 最鄰近節點,讀操作在最鄰近的成員,可能是主節點或者從節點。  --><bean id="nearestReadPreference" class="com.mongodb.TaggableReadPreference.NearestReadPreference"></bean><!-- 從節點,讀操作只在從節點, 如果從節點不可用,報錯或者拋出異常。存在的問題是secondary節點的資料會比primary節點資料舊。  --><bean id="secondaryReadPreference" class="com.mongodb.TaggableReadPreference.SecondaryReadPreference"></bean><!-- 優先從secondary節點進行讀取操作,secondary節點不可用時從主節點讀取資料  --><bean id="secondaryPreferredReadPreference" class="com.mongodb.TaggableReadPreference.SecondaryPreferredReadPreference"></bean><!-- mongodb的主要操作對象,所有對mongodb的增刪改查的操作都是通過它完成 --><bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"><constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /><property name="readPreference" ref="primaryPreferredReadPreference" /></bean><!-- 映射轉換器,掃描back-package目錄下的檔案,根據注釋,把它們作為mongodb的一個collection的映射 --><mongo:mapping-converter base-package="dev.lzq.uba.mongo.model" /><!-- mongodb bean的倉庫目錄,會自動掃描擴充了MongoRepository介面的介面進行注入 --><mongo:repositories base-package="dev.lzq.uba.mongo.dao" />


  • entity

@Document(collection = "user")public class User {@Idprivate int id;private String name;private int age;private String city;private String mote;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getMote() {return mote;}public void setMote(String mote) {this.mote = mote;}}


  • dao配置

public interface MGUserDao extends MongoRepository<User, ObjectId>{/** * 方法名的嚴格遵守規定 * @param age * @param page * @return */public Page<User> findByAgeGreaterThan(int age, Pageable page);/** * 有@Query聲明查詢, 方法名不需要嚴格遵守規定 * @param name * @param ageFrom * @param ageTo * @param pageable * @return */@Query("{‘name‘:{‘$regex‘:?0}, ‘age‘: {‘$gte‘:?1,‘$lte‘:?2}}")public Page<User> findByNameAndAgeRange(String name, int ageFrom, int ageTo, Pageable pageable);@Query("{?0:?1}")public List<User> findByAttribute(String key, String value);}


  • dao層的使用

    MongoRepository實現了的只是最基本的增刪改查的功能,要想增加額外的查詢方法,可以按照以下規則定義介面的方法。自訂查詢方法,格式為“findBy+欄位名+方法尾碼”,方法傳進的參數即欄位的值,此外還支援分頁查詢,通過傳進一個Pageable對象,返回Page集合。 例如:

//查詢大於age的資料 public Page<Product> findByAgeGreaterThan(int age,Pageable page) ;

    

    下面是支援的查詢類型,每三條資料分別對應:(方法尾碼,方法例子,mongodb原生查詢語句)

GreaterThan(大於) findByAgeGreaterThan(int age) {"age" : {"$gt" : age}}LessThan(小於) findByAgeLessThan(int age) {"age" : {"$lt" : age}}Between(在...之間) findByAgeBetween(int from, int to) {"age" : {"$gt" : from, "$lt" : to}}IsNotNull, NotNull(是否非空) findByFirstnameNotNull() {"age" : {"$ne" : null}}IsNull, Null(是否為空白) findByFirstnameNull() {"age" : null}Like(模糊查詢) findByFirstnameLike(String name) {"age" : age} ( age as regex)(No keyword) findByFirstname(String name) {"age" : name}Not(不包含) findByFirstnameNot(String name) {"age" : {"$ne" : name}}Near(查詢地理位置相近的) findByLocationNear(Point point) {"location" : {"$near" : [x,y]}}Within(在地理位置範圍內的) findByLocationWithin(Circle circle) {"location" : {"$within" : {"$center" : [ [x, y], distance]}}}Within(在地理位置範圍內的) findByLocationWithin(Box box) {"location" : {"$within" : {"$box" : [ [x1, y1], x2, y2]}}}


    儘管以上查詢功能已經很豐富,但如果還不能滿足使用方式的話可以用一下方法---基於mongodb原本查詢語句的查詢方式。

    例一:在原介面中加入,注釋Query裡面的就是mongodb原來的查詢文法,我們可以定義傳進來的查詢參數,通過座標定義方法的參數。

@Query("{ ‘name‘:{‘$regex‘:?2,‘$options‘:‘i‘}, sales‘: {‘$gte‘:?1,‘$lte‘:?2}}")public Page<Product> findByNameAndAgeRange(String name,double ageFrom,double ageTo,Pageable page);

    例二:還可以在後面指定要返回的資料欄位,如上面的例子修改如下,則只通過person表裡面的name和age欄位構建person對象。

@Query(value="{ ‘name‘:{‘$regex‘:?2,‘$options‘:‘i‘}, sales‘:{‘$gte‘:?1,‘$lte‘:?2}}",fields="{ ‘name‘ : 1, ‘age‘ : 1}") public Page<Product> findByNameAndAgeRange(String name,double ageFrom,double ageTo,Pageable page);


本文出自 “架構師之路” 部落格,請務必保留此出處http://lizhuquan0769.blog.51cto.com/2591147/1763571

【MongoDB】spring-data-mongo配置

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.