1.添加Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.application.properties配置
spring.data.mongodb.host=172.22.3.174
spring.data.mongodb.port=27017
spring.data.mongodb.database=data
spring.data.mongodb.username=root
spring.data.mongodb.password=123456
3.User定义
@Document(collection="user")
public class User {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
4.UserService定义
@Service
public class UserService {
@Autowired
private MongoTemplate mongoTemplate;
public void save(User user) {
if (Objects.isNull(user)) {
throw new NullPointerException("user is null.");
}
mongoTemplate.save(user);
}
public void deleteUserByName(String name) {
Query query = new Query(Criteria.where("name").is(name));
mongoTemplate.remove(query, User.class);
}
public User queryUserByName(String name) {
Query query = new Query(Criteria.where("name").is(name));
return mongoTemplate.findOne(query, User.class);
}
public List<User> queryListByName(String name) {
Query query = new Query(Criteria.where("name").is(name));
return mongoTemplate.find(query, User.class);
}
public void updateAgeByName(String name, int age) {
Query query = new Query(Criteria.where("name").is(name));
Update update = new Update().set("age", age);
mongoTemplate.updateFirst(query, update, User.class);
}
public void updateListAgeByName(String name, int age) {
Query query = new Query(Criteria.where("name").is(name));
Update update = new Update().set("age", age);
mongoTemplate.updateMulti(query, update, User.class);
}
}
5.测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
private UserService userService;
@Test
public void addUserTest() {
User user = new User();
user.setName("jack");
user.setAge(20);
userService.save(user);
}
@Test
public void deleteUserTest() {
userService.deleteUserByName("jack");
}
@Test
public void queryUserTest() {
User user = userService.queryUserByName("jack");
System.out.println(user);
}
@Test
public void queryListTest() {
List<User> userList = userService.queryListByName("jack");
System.out.println(userList);
}
@Test
public void updateUserTest() {
userService.updateAgeByName("jack", 100);
}
@Test
public void updateUserListTest() {
userService.updateListAgeByName("jack", 200);
}
}
源码:https://gitee.com/jsjack_wang/springboot-demo dev-mongodb02分支