添加数据
- 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);