当前位置:Gxlcms > 数据库问题 > spring boot 使用 mongodb

spring boot 使用 mongodb

时间:2021-07-01 10:21:17 帮助过:21人阅读

@Document(collection = "t_student") 2 @AllArgsConstructor 3 @Data 4 @Builder 5 @ToString 6 public class Student { 7 @Id 8 private int studentid; 9 10 @Field("studentname") 11 private String studentname; 12 13 @Field("studentage") 14 private int age; 15 16 }

这里感觉会很爽,只需要定义字段,不需要写构造函数,不需要写get set,只需要使用lombok 在pom中添加maven引用

1 <dependency>
2     <groupId>org.projectlombok</groupId>
3     <artifactId>lombok</artifactId>
4     <version>1.16.18</version>
5 </dependency>

并为每个实体添加注解就ok了

 

4. MongoDB 为我们提供了数据查询接口

默认的查询我们只需要集成接口就可以了,当然也可以自定义,我们这边就是用默认接口了:

1 @Repository
2 public interface StudentRepository extends MongoRepository<Student, ObjectId>
3 {
4 
5 }

5.最后在controller层中添加一个名为 addStudent的action


@RequestMapping("/addStudent")
public Student addStudent() {
return studentRepository.save(new Student(1, "妹子1", 18));
}

就可以插入数据了,mongodb在数据插入的时候回检查这个db和Collection是否存在,如果不存在则自己会新建。

 

spring boot 使用 mongodb

标签:lombok   class   开始   logs   private   build   模型   分享   rgs   

人气教程排行