標籤: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)