springboot整合mongodb

springboot整合mongodb

丁起男 72 2022-05-26

springboot整合mongodb

导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

添加配置

spring:
  data:
    mongodb:
      #格式:mongodb://用户名:密码@服务器ip:端口/数据库名
      uri: mongodb://localhost:27017/test
#      host: localhost
#      port: 27017
#      database: test

添加监听类(可选)

@Component
public class ApplicationReadyListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private MongoTemplate mongoTemplate;

    private static final String TYPEKEY = "_class";

    /**
     * 配置监听器,如果不加,那么插入时会添加一个_class字段
     * @param event
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        MongoConverter converter = mongoTemplate.getConverter();
        if (converter.getTypeMapper().isTypeKey(TYPEKEY)){
            ((MappingMongoConverter)converter).setTypeMapper(new DefaultMongoTypeMapper(null));
        }
    }
}

添加实体类

@Data
@Accessors(chain = true)
public class User {
    @Id
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private Date createTime;
}

MongoTemplate方式

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 新增
     */
    @Test
    void save() {
        User user = new User()
                .setId(2)//如果添加对象的id重复会变成修改
                .setUsername("zhangsan2")
                .setPassword("123")
                .setAge(20);
        mongoTemplate.insert(user);
    }

    /**
     * 批量添加
     */
    @Test
    void saveList(){
        List<User> list = new ArrayList<>();
        for (int i=0; i<=10; i++){
            list.add(new User()
                    .setId(i) //批量添加时id不能重复
                    .setUsername("user"+i)
                    .setPassword("123")
                    .setAge(20+i));
        }
        mongoTemplate.insertAll(list);
    }

    /**
     * 删除指定
     */
    @Test
    void delete(){
        mongoTemplate.remove(new Query(Criteria.where("_id").is(1)),User.class);
    }

    /**
     * 删除所有
     */
    @Test
    void deleteAll(){
        mongoTemplate.remove(new Query(),User.class);
    }

    /**
     * 修改
     */
    @Test
    void update(){
        mongoTemplate.updateMulti(new Query(Criteria.where("_id").is(1)),
                new Update().set("username","zhangsan"),User.class);
    }

    /**
     * 查询
     */
    @Test
    void select(){
        Query query = new Query();
        query.addCriteria(Criteria.where("age").gt(10));
        query.with(Sort.by("_id").descending());
        query.skip(1);
        query.limit(5);
        List<User> list = mongoTemplate.find(query, User.class);
        System.out.println(list);
    }

    /**
     * 删除集合
     */
    @Test
    void drop(){
        mongoTemplate.dropCollection(User.class);
    }

MongoRepository方式

创建dao层接口

public interface UserDao extends MongoRepository<User,Integer> {
}

使用

    @Autowired
    private UserDao userDao;

    /**
     * 添加
     */
    @Test
    void save(){
        User user = new User()
                .setId(1)
                .setUsername("zhangsan")
                .setPassword("123")
                .setAge(10)
                .setCreateTime(new Date());
        userDao.insert(user);
    }

    @Test
    void saveList(){
        List<User> list = new ArrayList<>();
        for (int i=1; i<10; i++){
            list.add(new User()
                    .setId(i)
                    .setUsername("user"+i)
                    .setPassword("123"+i)
                    .setAge(10+i)
                    .setCreateTime(new Date()));
        }
        userDao.insert(list);
    }

    /**
     * 删除指定
     */
    @Test
    void delete(){
        userDao.deleteById(1);
    }

    /**
     * 删除所有
     */
    @Test
    void deleteAll(){
        userDao.deleteAll();
    }

    /**
     * 修改
     */
    @Test
    void update(){
        User user = new User()
                .setId(1)//id重复即为修改
                .setUsername("lisi")
                .setPassword("123")
                .setAge(10);
        userDao.save(user);
    }

	/**
     * 查询
     */
    @Test
    void select(){
        //条件
        User user = new User().setUsername("user2");
        //条件构造器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withIgnoreCase()//忽略大小写
                .withMatcher("username",ExampleMatcher.GenericPropertyMatcher::exact);//精准匹配
        Example<User> example = Example.of(user,matcher);
        //排序
        Sort sort = Sort.by("_id").descending();
        //分页
        PageRequest pageRequest = PageRequest.of(0, 5, sort);
        //查询数量
        long count = userDao.count(example);
        System.out.println(count);
        //查询数据
        Page<User> userPage = userDao.findAll(example, pageRequest);
        userPage.get().forEach(System.out::println);
    }