springboot整合MongoDB测试demo 代码
demo分为4个类,分别为: 学生实体类-student、课程实体类-course、springboot持久层-mongoDao、springboot控制层-mongoController
MongoDB不支持事务
mongodb 配置类
/**
* 描述:
* mongodb 配置类
* @author 闲走天涯
* @create 2021/7/24 14:10
*/
@Configuration
public class TransactionConfig {
@Bean
@ConditionalOnProperty(name="spring.data.mongodb.transactionEnabled",havingValue = "true")
public MongoTransactionManager transactionManager(MongoDbFactory factory){
return new MongoTransactionManager(factory);
}
}
1、学生实体类-student
注解进行声明对应的MongoDB 数据设置
/**
* 描述:
* 实体类-学生 student
* @author 闲走天涯
* @create 2021/7/23 13:53
*/
@Data
@Document(collection = "student") //声明对应集合的名称
@CompoundIndexes({ //声明复合索引 1为正序 -1为倒序
@CompoundIndex(name = "name_index",def = "{'name':1,'sex':1}")
})
public class Student implements Serializable {
// @Id 标识自定义 主键id,不使用系统自带的id(这里使用会导致报错)
@Field(value = "id")//声明在mongo中的字段名称
@Indexed(unique = true) //索引
private String id;
@Field(value = "name")
private String name;
@Field(value = "birth")
private String birth;
@Field(value = "sex")
private String sex;
@DBRef
private List<Course> courses;
@Transient //声明为普通的bean 属性,不参与mongo
private String age;
@Transient
private String order;
@Transient
private Integer by;
}
2、课程实体类-student
/**
* 描述:
* 实体类-课程 course
* @author 闲走天涯
* @create 2021/7/23 16:10
*/
@Data
@Document(collection = "course")
public class Course implements Serializable {
@Id
@Field(value = "id")
private String id;
@Field(value = "name")
private String name;
@Field(value = "code")
private String code;
}
3、Springboot MongoDB持久层
/**
* 描述:
* Springboot MongoDB测试-持久层
* @author 闲走天涯
* @create 2021/7/23 13:53
*/
@Repository
public class MongoDao {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 新增
* @param student
* @return
*/
public Student insert(Student student){
if(student!=null && student.getCourses()!=null && student.getCourses().size()>0){
for(Course course:student.getCourses()){
mongoTemplate.save(course);
}
}
Student model = mongoTemplate.save(student);
return model;
}
/**
* 修改
* @param student
* @return 更新的文档数
*/
public Long update(Student student){
Query query = new Query(Criteria.where("id").is(student.getId()));
Update update = new Update();
if(VerifyData.strIsNotNull(student.getName())){
update.set("name",student.getName());
}
if(VerifyData.strIsNotNull(student.getBirth())){
update.set("birth",student.getBirth());
}
if(VerifyData.strIsNotNull(student.getSex())){
update.set("sex",student.getSex());
}
UpdateResult result = mongoTemplate.updateFirst(query,update,Student.class);
return result.getModifiedCount();
}
/**
* 根据id查询
* @param id
* @return
*/
public Student findById(String id){
Student result = mongoTemplate.findById(id,Student.class);
return result;
}
/**
* 条件查询
* 这种方式不能全部为空查询
* @param model
* @return
*/
public List<Student> find_and(Student model){
List<Criteria> list = new ArrayList<>();
if (VerifyData.strIsNotNull(model.getId())) {
//等值查询 is
Criteria criteria = Criteria.where("id").is(model.getId());
list.add(criteria);
}
if (VerifyData.strIsNotNull(model.getName())) {
//模糊查询 regex
Criteria criteria = Criteria.where("name").regex(model.getName());
list.add(criteria);
}
if (VerifyData.strIsNotNull(model.getBirth())) {
Criteria criteria = Criteria.where("birth").is(model.getBirth());
list.add(criteria);
}
if (VerifyData.strIsNotNull(model.getSex())) {
Criteria criteria = Criteria.where("sex").is(model.getSex());
list.add(criteria);
}
Criteria[] cri_arr = new Criteria[list.size()];
list.toArray(cri_arr);
Criteria criteria = new Criteria().andOperator(cri_arr);
//查询-或 Criteria criteria = new Criteria().orOperator(cri_arr);
Query query = new Query(criteria);
//order by birth desc
query.with(new Sort(Sort.Direction.DESC,"birth"));
List<Student> result = mongoTemplate.find(query,Student.class);
return result;
}
/**
* 条件查询
* 可以全部查询-无条件查询
* @param model
* @return
*/
public List<Student> find_and2(Student model){
Criteria criteria = new Criteria();
if(VerifyData.strIsNotNull(model.getId())){
//等值查询 is
criteria.and("id").is(model.getId());
}
if(VerifyData.strIsNotNull(model.getName())){
//模糊查询 regex
criteria.and("name").regex(model.getName());
}
if(VerifyData.strIsNotNull(model.getBirth())){
criteria.and("birth").is(model.getBirth());
}
if(VerifyData.strIsNotNull(model.getSex())){
criteria.and("sex").is(model.getSex());
}
Query query = new Query(criteria);
//order by birth desc
if(VerifyData.strIsNotNull(model.getOrder())){
Sort.Direction direction = Sort.Direction.DESC;
if(VerifyData.intIsNotNullOrZero(model.getBy()) && model.getBy()==1) {
direction = Sort.Direction.ASC;
}
query.with(new Sort(direction,model.getOrder()));
}else{
query.with(new Sort(Sort.Direction.DESC,"id"));
}
List<Student> result = mongoTemplate.find(query,Student.class);
return result;
}
/**
* 课程条件查询
* 可以全部查询-无条件查询
* @param model
* @return
*/
public List<Course> find_course(Course model){
Criteria criteria = new Criteria();
if(VerifyData.strIsNotNull(model.getId())){
//等值查询 is
criteria.and("id").is(model.getId());
}
if(VerifyData.strIsNotNull(model.getName())){
//模糊查询 regex
criteria.and("name").regex(model.getName());
}
if(VerifyData.strIsNotNull(model.getCode())){
criteria.and("code").is(model.getCode());
}
Query query = new Query(criteria);
//order by id desc
query.with(new Sort(Sort.Direction.DESC,"id"));
List<Course> result = mongoTemplate.find(query,Course.class);
return result;
}
/**
* 删除id
* @param id
* @return
*/
public Long deleteById(String id){
Query query = new Query(Criteria.where("id").is(id));
DeleteResult result = mongoTemplate.remove(query,Student.class);
return result.getDeletedCount();
}
}
4、Springboot MongoDB控制层
/**
* 描述:
* springboot MongoDB测试-controller
* @author 闲走天涯
* @create 2021/7/23 14:09
*/
@RestController
@RequestMapping("/mongo")
public class MongoController {
@Autowired
private MongoDao mongoDao;
/**
* 新增
* @param student
* @return
*/
@RequestMapping("/insert")
public Student insert(@RequestBody Student student){
try {
return mongoDao.insert(student);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 修改
* @param student
* @return 更新的文档数
*/
@RequestMapping("/update")
public Long update(Student student){
try {
return mongoDao.update(student);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 根据name查询
* @param id
* @return
*/
@RequestMapping("/findById")
public Student findById(String id){
try {
return mongoDao.findById(id);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 条件查询
* @return
*/
@RequestMapping({"/find/{collection}","/find"})
public JsonBean find(Student student,Course course, @PathVariable(value = "collection",required = false) String collection){
try {
if(VerifyData.strIsNotNull(collection) && "course".equals(collection)){
List<Course> list = mongoDao.find_course(course);
return new JsonBean(JsonStatus.SUCCESS,list);
}else {
List<Student> list = mongoDao.find_and2(student);
return new JsonBean(JsonStatus.SUCCESS,list);
}
}catch (Exception e){
e.printStackTrace();
return new JsonBean(JsonStatus.EXCEPTION,"查询异常",null);
}
}
/**
* 删除id
* @param id
* @return
*/
@RequestMapping("/deleteById")
public Long deleteById(String id){
try {
return mongoDao.deleteById(id);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
/**
* 结果信息返回类型
* @param <T>
*/
@Data
class JsonBean<T>{
private String code;
private String msg;
private T data;
public JsonBean(JsonStatus code, String msg, T data) {
this.code = code.getCode();
this.msg = msg;
this.data = data;
}
public JsonBean(JsonStatus code, T data) {
this.code = code.getCode();
this.msg = code.getMsg();
this.data = data;
}
}
/**
* 枚举-返回结果信息
*/
enum JsonStatus{
SUCCESS("success","查询成功"),
FAILD("faild","查询失败"),
EXCEPTION("exception","查询异常");
private String code;
private String msg;
JsonStatus(String code){
this.code=code;
}
JsonStatus(String code,String msg){
this.code=code;
this.msg=msg;
}
public String getCode() {
return code;
}
public String getMsg() {
return msg;
}
}