springboot(java)操作mongodb创建工程 作者:马育民 • 2021-08-13 07:58 • 阅读:10049 # 创建maven工程 略 # pom.xml 依赖 需要用到: ``` org.springframework.boot spring-boot-starter-data-mongodb 2.2.0.RELEASE ``` 还需要junit用于测试: ``` org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine ``` ### 完整 ``` org.springframework.boot spring-boot-dependencies 2.2.2.RELEASE pom import org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-mongodb 2.2.0.RELEASE org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine ``` # application.properties ``` spring.data.mongodb.uri=mongodb://localhost:27017/blog ``` # 实体类 ``` @Document(collection = "user") public class User implements Serializable { @Id private String id; private String username; private String password; private String name; private String sex; private Integer age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + '}'; } } ``` # 主启动类 ``` @SpringBootApplication public class Main { public static void main(String[] args) { SpringApplication.run(Main.class,args); } } ``` # junit 在 `/test/java` 下创建测试类: ``` @SpringBootTest public class Test { @Resource private MongoTemplate mt; @org.junit.jupiter.api.Test public void add(){ String uuid= UUID.randomUUID().toString().replace("-",""); User user=new User(); user.setId(uuid); user.setUsername("lucy"); user.setPassword("123456"); user.setName("lucy"); user.setAge(20); user.setSex("女"); mt.insert(user); } ``` 原文出处:http://malaoshi.top/show_1IX1fPqX9Oje.html