Spring boot集成mongodb,MongoTemplate、MongoRepository开发CRUD
一、创建Springboot工程
使用Spring Initializr 快速初始化一个 Spring Boot 工程,引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.1</version> </dependency>
添加配置
在application.yml文件增加配置
spring:
data:
mongodb:
uri: mongodb://192.168.56.20:27017/test
PS:由于我是将MongoDB安装在虚拟机中,所以需要在MongoDB的配置文件中添加 bind_ip = 0.0.0.0 以允许远程访问。
二、MongoTemplate 开发CRUD
创建实体类
package com.aiden.mongodb.entity; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; /** * @author guoxiangyue */ @Data @Document("User") public class User { @Id private String id; private String name; private Integer age; private String email; private String createDate; }
创建测试类,功能测试实现
package com.aiden.mongodb; import com.aiden.mongodb.entity.User; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; @SpringBootTest class MongodbApplicationTests { @Autowired private MongoTemplate mongoTemplate; /** * 添加 */ @Test void createUserTest(){ User user = new User(); user.setName("猪八戒"); user.setAge(12000); user.setEmail("zhubajie@xiyou.com"); User insert = mongoTemplate.insert(user); System.out.println(insert); } /** * 查找所有 */ @Test void findUser(){ List<User> userList = mongoTemplate.findAll(User.class); userList.forEach(System.out::println); } /** * 根据ID查找 */ @Test void findUserById(){ User user = mongoTemplate.findById("6064261c19218c5d764c687e", User.class); System.out.println(user); } /** * 条件查找 */ @Test void findUserList(){ Criteria criteria =Criteria.where("name").is("黑寡妇").and("age").is(30); Query query =new Query(criteria); List<User> users = mongoTemplate.find(query, User.class); users.forEach(System.out::println); } /** * 模糊查找 */ @Test void findUserLikeEmail(){ String email = "manwei"; String regex = String.format("%s%s%s","^.*",email,".*$"); System.out.println(regex); Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE); Query query = new Query(Criteria.where("email").regex(pattern)); List<User> userList = mongoTemplate.find(query, User.class); userList.forEach(System.out::println); } /** * 分页查找 */ @Test void findUsersPage(){ String email = "manwei"; int pageNo = 1; int pageSize = 3; String regex = String.format("%s%s%s","^.*",email,".*$"); Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE); Query query = new Query(); query.addCriteria(Criteria.where("email").regex(pattern)); int count = (int) mongoTemplate.count(query, User.class); query.skip((pageNo-1)*pageSize).limit(pageSize); List<User> userList = mongoTemplate.find(query, User.class); userList.forEach(System.out::println); Map<String, Object> pageMap = new HashMap<>(); pageMap.put("list", userList); pageMap.put("totalCount",count); System.out.println(pageMap); } /** * 更新 */ @Test void updateUser(){ User user = mongoTemplate.findById("606424a10e99ee35d4276f8e", User.class); user.setAge(25); user.setEmail("xiaozemaliya@riben.com"); Query query = new Query(Criteria.where("_id").is(user.getId())); Update update = new Update(); update.set("name", user.getName()); update.set("age", user.getAge()); update.set("email", user.getEmail()); UpdateResult result = mongoTemplate.upsert(query, update, User.class); long count = result.getModifiedCount(); System.out.println(count); } /** * 删除 */ @Test public void delete() { Query query = new Query(Criteria.where("_id").is("606425ef6d04814aca4e959e")); DeleteResult result = mongoTemplate.remove(query, User.class); long count = result.getDeletedCount(); System.out.println(count); } }
三、MongoRepository开发CRUD
添加Repository类
package com.aiden.mongodb.dao; import com.aiden.mongodb.entity.User; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; /** * @author guoxiangyue */ @Repository public interface UserRepository extends MongoRepository<User,String> { }
创建测试类,测试功能实现
package com.aiden.mongodb.dao; import com.aiden.mongodb.entity.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.*; import java.util.List; @SpringBootTest class UserRepositoryTest { @Autowired private UserRepository userRepository; //添加 @Test public void createUser() { User user = new User(); user.setAge(10); user.setName("浩克"); user.setEmail("haoke@manwei.com"); User user1 = userRepository.save(user); System.out.println(user1); } /** * 查询所有 */ @Test public void findAll(){ List<User> userList = userRepository.findAll(); userList.forEach(System.out::println); } /** * ID查询 */ @Test public void findUserById(){ User user = userRepository.findById("6064264e1bd90356f6cae98e").get(); System.out.println(user); } /** * 条件查询 */ @Test public void findUserList(){ User user = new User(); user.setAge(20); Example<User> example =Example.of(user); List<User> userList = userRepository.findAll(example); userList.forEach(System.out::println); } //模糊查询 @Test public void findUsersLikeEmail(){ //创建匹配器 ExampleMatcher matcher = ExampleMatcher.matching() //改变默认字符串匹配方式:模糊查询 .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认大小写忽略方式:忽略大小写 .withIgnoreCase(true); User user = new User(); user.setEmail("man"); Example<User> userExample = Example.of(user, matcher); List<User> userList = userRepository.findAll(userExample); userList.forEach(System.out::println); } //分页查询 @Test public void findUsersPage() { Sort sort = Sort.by(Sort.Direction.DESC, "age"); Pageable pageable = PageRequest.of(0, 2, sort); //创建匹配器,即如何使用查询条件 ExampleMatcher matcher = ExampleMatcher.matching() //构建对象 .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式:模糊查询 .withIgnoreCase(true); //改变默认大小写忽略方式:忽略大小写 User user = new User(); user.setEmail(".com"); //创建实例 Example<User> example = Example.of(user, matcher); Page<User> pages = userRepository.findAll(example, pageable); pages.get().forEach(System.out::println); } //修改 @Test public void updateUser() { User user = userRepository.findById("60642578b9f77c7edd78fee4").get(); user.setName("齐天大圣"); User save = userRepository.save(user); System.out.println(save); } //删除 @Test public void delete() { userRepository.deleteById("60642578b9f77c7edd78fee4"); } }