1.MongoTemplate方式
1.1pom.xml配置
<!-- mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
1.2项目目录
1.3User.java
package com.shuai.spring_boot_1.domain;
import org.springframework.data.annotation.Id;
public class User {
//id属性是给mongodb用的,用@Id注解修饰
@Id
private String id;
private String name;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
1.4OneController.java
package com.shuai.spring_boot_1.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.shuai.spring_boot_1.domain.User;
@RestController
public class OneController {
@Autowired
private MongoTemplate mongoTemplate;
@RequestMapping("/save")
public String save(){
User user = new User();
user.setId("2");
user.setName("李四");
user.setAge(10);
mongoTemplate.save(user);
System.out.println("保存成功");
return "ok";
}
@RequestMapping("/find")
public String find(){
List<User> findAll = mongoTemplate.findAll(User.class);
System.out.println(findAll);
return "ok";
}
}
1.5App.java
package com.shuai.spring_boot_1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
1.6运行项目
运行App.java中的main方法
1.7访问项目
http://localhost:8080/save 保存
http://localhost:8080/find 获取全部