spring mongodb增刪改查操做

添加數據

  • School
@Id
@GeneratedValue
private long id;
@Indexed(unique = true)
private String name;
  • student
@Id
@Field("_id")
private String id;
private String name;
@DBRef
private School school;
  • dao
public interface SchoolRepository extends MongoRepository<School, Long> {
}
public interface StudentRepository extends MongoRepository<Student, String> {
}
  • 添加數據
School s1 = new School("淮陰工學院");
School s2 = new School("南京大學");
schoolRepository.save(s1);
schoolRepository.save(s2);

Student s1 = new Student("張三", new School(1));
Student s2 = new Student("李四", new School(1));
studentRepository.save(s1);
studentRepository.save(s2);

刪除數據

刪除一個學校試試?java

schoolRepository.deleteById(1L);

刪除學校後,發現引用該學校的學生沒有被刪除spa

  • 查詢學生試試看?

所以,須要本身來維護關係,若有須要,本身手動級聯刪除3d

查詢

使用基於接口的動態代理類- MongoRepository<>

List<Outline> findOutlineByNameAndCourse(String name, Course course);
  • 分頁查詢
//建立匹配器,即如何使用查詢條件
ExampleMatcher matcher = ExampleMatcher.matching() //構建對象
        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改變默認字符串匹配方式:模糊查詢
        .withIgnoreCase(true) //改變默認大小寫忽略方式:忽略大小寫
        .withMatcher("articleTitle", ExampleMatcher.GenericPropertyMatchers.contains()); //採用「包含匹配」的方式查詢
Example<Article> example = Example.of(article, matcher);
Page<Article> data = articleRepository.findAll(example, page);

MongoDBTemplate

  • Query
Pattern pattern = Pattern.compile("^.*" + key + ".*$", Pattern.CASE_INSENSITIVE);
Query query = Query.query(Criteria.where("name").regex(pattern).and("grade").is(new Grade(gradeId)));
query.limit(20);
List<Course> courses = mongo.find(query, Course.class);

忽略大小寫代理

Criteria.where("name").regex("admin", "i")

修改

  • 使用mongoTempalte
// 條件
Criteria where = Criteria.where("username").is("admin");
Query query = Query.query(where);
Update update = new Update();
update.set("username", "admin66");
UpdateResult upsert = mongoOperations.upsert(query, update, User.class);
相關文章
相關標籤/搜索