导入依赖
org.springframework.boot spring-boot-starter-data-mongodb
.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 {}
注入调用
@Servicepublic class MyUserNondbService { @Resource private MyUserMongodb myUserMongodb; public MyUser save() { //对象对象 MyUser myUser = new MyUser("bbb"); //存储,返回新插入的数据 return myUserMongodb.save(myUser); }}
@RestControllerpublic class AController { @Autowired private MyUserNondbService myUserNondbService; @RequestMapping(path = "/test") public Object test(){ return myUserNondbService.save(); }}