mongodb學習一(使用mongoResposity)

來源:互聯網
上載者:User

標籤:class   dex   xtend   data   方法   wired   name   ext   串連   

最近公司做一個項目用到了mongodb,下面來介紹一下MongoRepository介面。

大家可以類比Hibernate的jpa,MongoRepository是一個springdata提供的一個有增刪改查以及分頁等操作的基本介面。

我們在使用介面時,只需要定義一個dao層的介面,例如:

interface UserResposity extends MongoRepository<User, String>{},   User是一個entity實體類。

下面貼上User實體類

 1 @Data 2 @Document(collection = "User") 3 public class User implements Serializable { 4  5     @Id 6     private String id; 7  8     /** 9      * 電話10      */11     @Indexed(unique = true)12     private String telephone;13 14 15     /**16      * 暱稱17      */18     @Indexed19     private String nickname;20 21     /**22      * 頭像地址23      */24     private String avatar;25 26 27     /**28      * 出生日期29      */30     private Long birthday;31 32     /**33      * 性別34      *35      */36     private Integer sex;37 38  39     /**40      * 關注使用者的集合41      */42     private List<String> followingList;43 44 45 46 }

UserResposity介面代碼如下:

1 @Repository2 public interface UserRepository extends MongoRepository<User, String> {3 4     User findByTelephone(String telephone);5 }

我們只需要書寫介面,不用自己去寫介面的實現。例如findByTelephone方法,telephone是User類的一個屬性

介面方法的基本命名方式為  find + By + 實體類屬性名稱(首字母大寫)+查詢條件(首字母大寫)

查詢條件就是Like,用過SQL的大家都知道,就是模糊查詢的意思。

還有GreaterThan(大於) ,LessThan(小於) ,Between(在...之間), IsNotNull, NotNull(是否非空),Near(查詢地理位置相近的)等。具體查看官網文檔 https://docs.spring.io/spring-data/mongodb/docs/1.10.13.RELEASE/reference/html/#repositories.definition

如果需要查詢的方法有多個欄位可以用And來串連即可。

如果要使用這個介面,需要把介面注入。代碼如下:

 1 @Autowired 2 private UserRepository userRepository; 

 

mongodb學習一(使用mongoResposity)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.