一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
二、配置MongoDB链接
spring:
data:
mongodb:
host: 127.0.0.1
port: 27017
database: test
三、实体类
@Document(collection = "student")
public class Student implements Serializable {
@Id
private String id;
private String name;
private String address;
private int sex;
}
四、Service类
@Service
public class StudentService {
private MongoTemplate mtl;
@Autowired
public StudentService(MongoTemplate mtl) {
this.mtl = mtl;
}
public void saveStudent(Student student){
mtl.save(student);
}
public void saveStudents(List<Student> studentlist){
mtl.insert(studentlist);
}
public void updateStudent(Student student){
mtl.save(student);
}
public List<Student> findAllStudent(){
return mtl.findAll(Student.class);
}
public Student findStudentById(String id){
return mtl.findById(id,Student.class);
}
public List<Student> findStudentByName(String name){
Query query = new Query(Criteria.where("name").is(name));
return mtl.find(query, Student.class);
}
public List<Student> findStudentByAddress(String address){
Pattern pattern=Pattern.compile("^.*"+address+".*$", Pattern.CASE_INSENSITIVE);
Query query = new Query(Criteria.where("name").regex(pattern));
return mtl.find(query, Student.class);
}
public List<Student> findMaleStudentByName(String name){
Query query = new Query(new Criteria().andOperator(Criteria.where("name").is(name), Criteria.where("sex").is(0)));
return mtl.find(query, Student.class);
}
public List<Student> findStudentByNameWithPage(String name, int nowPage){
Query query = new Query(Criteria.where("name").is(name));
Pageable mypage = PageRequest.of(nowPage-1,10);
query.with(mypage);
return mtl.find(query,Student.class);
}
public void deleteStudent(Student student){
mtl.remove(student);
}
}
五、Query的使用方法
Query:
精准条件:Criteria.where(“key”).is(“条件”)
模糊条件:Criteria.where(“key”).regex(“条件”)
判断大小:gt:大于 lt:小于 gte:大于等等 lte:小于等于
或条件:new Criteria().orOperator(“条件”)
与条件:new Criteria().andOperator(“条件”)
封装条件:query.addCriteria(criteria)
分页:Pageable mypage = PageRequest.of(nowPage-1,10);
query.with(mypage);
排序:query.with(Sort.by(Sort.Order.desc("creatTime")));
query.with(Sort.by(Sort.Order.asc("creatTime")));
Tips:进行日期查询时只需将JAVA中得到的日期作为条件即可,而不用像其他教程中所说的转换后在查询。
具体原因作为小白,我也不是很清楚。但是查询出的结果确实准确,按其他教程来程序并不能得到结果。