Springboot配置mongodb
作者:互联网
-
导入依赖
<!-- MongoDB --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
-
.yaml配置
spring: data: mongodb: host: 127.0.0.1 //IP port: 27017 //端口 database: mytest //库名
-
创建bean( 类名的小驼峰为集合名 )
例:
public class MyUser { private String name; public MyUser() { } public MyUser(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
-
建立连接
public interface MyUserMongodb extends MongoRepository<MyUser,String> { }
-
注入调用
@Service public class MyUserNondbService { @Resource private MyUserMongodb myUserMongodb; public MyUser save() { //对象对象 MyUser myUser = new MyUser("bbb"); //存储,返回新插入的数据 return myUserMongodb.save(myUser); } }
@RestController public class AController { @Autowired private MyUserNondbService myUserNondbService; @RequestMapping(path = "/test") public Object test(){ return myUserNondbService.save(); } }
标签:Springboot,MyUser,配置,private,String,mongodb,save,public,name 来源: https://blog.csdn.net/m0_50163856/article/details/115570425