1.在基础组件已经搭建完成的项目里添加 mongodb pom依赖
<!--mongodb依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.yml 或者properties配置文件里加入mongodb数据源配置信息,下面以yml为例
spring:
data:
mongodb:
#mongodb设置了密码时 ip为mongodb所在ip
#注意:username和password中含有“:”或“@”需要进行URLEncoder编码
uri: mongodb://dbUserName:dbPassword@ip:27017/dbName
#mongodb未设置密码时 ip为mongodb所在ip
uri: mongodb://ip:27017/dbName
3.创建文档表 映射类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
import java.util.Date;
/**
* 测试mongodb的测试类
*/
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Data
@Document(collection = "Student") //映射mongodb库中Student文档表
public class Student implements Serializable {
@Id// 必须指定id列
private String studentId;
private String studentName;
private Integer studentAge;
private Double studentScore;
private Date studentBirthday;
}
3.创建文档表对应的dao层
方式一:这种写法不需要写实现类
import com.midea.cloud.user.entity.Student;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
/*
*
* 这里的用法其实和SpringDataJPA相似, 可根据需要来自定义方法
* 这种写法不需要写实现类
*
* MongoRepository<行对应的对象类型, 主键列类型>
* */
public interface StudentRepository extends MongoRepository<Student, String> {
// 可根据需求自己定义方法, 无需对方法进行实现
List<Student> getAllByStudentName(String studentName);
}
使用时,注入StudentRepository 即可:
@Autowired
private StudentRepository studentRepository;
方式二:mongoTemplate形式
使用时,注入MongoTemplate
@Autowired
private MongoTemplate mongoTemplate;
public List<Student> getAllByStudentName(String name) {
//方式一 条件查询
List<Student> list1 = studentRepository.getAllByStudentName(name);
System.out.println("方式1:"+list1.toString());
//方式二 条件查询
Criteria criteria = Criteria.where("studentName").is(name);
Query query = new Query(criteria);
List<Student> list = mongoTemplate.find(query, Student.class);
System.out.println("方式2:"+list.toString());
return list;
}
补充:
在mongorepository中,还有对于其他一些查询的操作
注意遵循mongo repository相关原则
大于某个值
findByAgeGreaterThan+ParameterName(IntegerParameter)
小于某个值
findByAgeLessThan+ParameterName((IntegerParameter)
判断是否空值
findBy+ParameterName+Null(String Parameter)
判断是否非空值
findBy+ParameterName+NotNull(String Parameter)
不包含某个值
findBy+ParameterName+Not(String Parameter)
在某个范围
findBy+ParameterName+Between(Integer Parameter, Integer Parameter)
模糊查询
findBy+ParameterName+Like(Integer Parameter)