MongoDB学习笔记四

目录

1.简介

2.环境搭建

2.1引入pom依赖

2.2配置yaml

3.编写一个简单增删改查类(这里使用mongotemplate操作)

3.1常用方法

3.2解释说明

3.3代码实现

4.编写一个简单增删改查类(这里使用mongorepository操作)


这期讲如何使用java操作mongodb

1.简介

spring-data-mongodb提供了MongoTemplate与MongoRepository两种方式访问mongodb,MongoRepository操作简单,MongoTemplate操作灵活,我们在项目中可以灵活适用这两种方式操作mongodb,MongoRepository的缺点是不够灵活,MongoTemplate正好可以弥补不足。

2.环境搭建

2.1引入pom依赖



    org.springframework.boot
    spring-boot-starter-web



    org.springframework.boot
    spring-boot-starter-test
    test
    
        
            org.junit.vintage
            junit-vintage-engine
        
    



    org.springframework.boot
    spring-boot-starter-data-mongodb

2.2配置yaml

spring:
  data:
    mongodb:
      uri: mongodb://127.0.0.1:27017/test

3.编写一个简单增删改查类(这里使用mongotemplate操作)

3.1常用方法

mongoTemplate.insert(User): 新增
mongoTemplate.save(User): 新增
mongoTemplate.upsert(query, update, User.class): 修改
mongoTemplate.remove(query, User.class): 删除
mongoTemplate.findAll(User.class): 查询User文档的全部数据
mongoTemplate.findById(, User.class): 查询User文档id为id的数据
mongoTemplate.find(query, User.class);: 根据query内的查询条件查询

3.2解释说明

观看下列代码可以发现,经常使用到俩个对象一个是Query一个是Criteria,这里对这俩个对象做一个小小的解释:

Query:可以把他理解为一个条件语句,把他当作mybatis中的的标签来看待,里面封装的是条件语句,用于处理对数据库的增删改查操作

Criteria:可以把它理解为一个具体的条件语句,当作是sql中的where、and、or、like等等这类特殊条件语句

3.3代码实现

实体对象类:

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Data
@Document("User")
public class User {

    @Id
    @JsonIgnore // 隐藏该字段,不在前台swagger中展示
    private String id;

    private String name;

    private Integer age;

    private String sex;

    private String address;

    private String email;
    @JsonIgnore // 隐藏该字段,不在前台swagger中展示
    private String createDate;
    @JsonIgnore // 隐藏该字段,不在前台swagger中展示
    private String updateDate;

    @Override
    public String toString() {
        return "User{" +
                "用户名 = " + name +
                ", 年龄 = " + age +
                ", 性别 = " + sex +
                ", 地址 = " + address +
                ", 邮箱 = '" + email +
                '}';
    }

}

接口类:

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.mongodemo.domain.User;
import org.example.mongodemo.service.MongoDemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController("/mongodemo")
@Api(tags = "MongoDemo测试接口")
public class MongoDemoContrller {

    @Autowired
    private MongoDemoService mongoDemoService;

    @GetMapping("/getUsers")
    @ApiOperation(value = "获取用户列表", notes = "获取所有用户列表信息")
    public String getUsers() {
        return mongoDemoService.getUsers();
    }

    @GetMapping("/getUser/{id}")
    @ApiOperation(value = "根据id获取用户", notes = "根据id获取用户详细信息")
    public String getUserById(@PathVariable String id) {
        return mongoDemoService.getUserById(id);
    }

    @DeleteMapping("/delUser/{id}")
    @ApiOperation(value = "根据id删除用户", notes = "根据id删除用户详细信息数据")
    public String delUserById(@PathVariable String id) {
        return mongoDemoService.delUserById(id);
    }

    @PutMapping("/addUser")
    @ApiOperation(value = "添加用户", notes = "添加用户信息")
    public String addUser(@RequestBody User user) {
        return mongoDemoService.addUser(user);
    }

    @PostMapping("/updateUser")
    @ApiOperation(value = "编辑用户", notes = "编辑用户信息")
    public String updateUser(
            @RequestParam String id,
            @RequestBody User user) {
        return mongoDemoService.updateUser(id, user);
    }

    @PostMapping("/getUserByCondition")
    @ApiOperation(value = "条件模糊查询用户", notes = "条件模糊查询用户信息")
    public String getUserByCondition(@RequestBody Map data) {
        return mongoDemoService.getUserByCondition(data);
    }


}

service接口:

import org.example.mongodemo.domain.User;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public interface MongoDemoService {

    String getUsers();

    String addUser(User user);

    String getUserById(String id);

    String delUserById(String id);

    String updateUser(String id, User user);

    String getUserByCondition(Map data);
}

service实现类:

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.DeleteResult;
import org.apache.commons.lang3.StringUtils;
import org.example.mongodemo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;

@Service
public class MongoDemoServiceImpl implements MongoDemoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    private final String dbName = "user.userdata";

    @Override
    public String getUsers() {
        List userList = mongoTemplate.findAll(User.class, dbName);
        ListIterator iterator = userList.listIterator();
        while (iterator.hasNext()) {
            System.out.println("====>>> 对象数据打印: " + iterator.next());
        }
        return JSON.toJSON(userList).toString();
    }

    @Override
    public String addUser(User user) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(new Date(System.currentTimeMillis()));
        user.setCreateDate(format);
        user.setUpdateDate(format);
        User saveUser = mongoTemplate.save(user, dbName);
        System.out.println(saveUser);
        return "添加成功,生成id: "+saveUser.getId();
    }

    @Override
    public String getUserById(String id) {
        User user = mongoTemplate.findById(id, User.class, dbName);
        if (Optional.ofNullable(user).isEmpty()){
            return "查无此人!";
        }
        return user.toString();
    }

    @Override
    public String delUserById(String id) {
        // 使用mongodb包中得Criteria组装查询条件
        Criteria criteria = Criteria.where("_id").is(id);
        // 封装Query查询对象
        Query query = new Query().addCriteria(criteria);
        // 删除
        DeleteResult remove = mongoTemplate.remove(query, dbName);
        long count = remove.getDeletedCount();
        if (count == 1){
            return "删除成功";
        }
        return "删除失败";
    }

    @Override
    public String updateUser(String id, User user) {
        User oldUser = mongoTemplate.findById(id, User.class, dbName);
        if (Optional.ofNullable(oldUser).isEmpty()) {
            return "用户不存在,请检查id是否输入正确";
        }
        // 构造mongo更新对象
        Update update = new Update();
        update.set("name", StringUtils.isNotBlank(user.getName())? user.getName() : oldUser.getName());
        update.set("age", StringUtils.isNotBlank(user.getAge().toString())? user.getAge() : oldUser.getAge());
        update.set("email", StringUtils.isNotBlank(user.getEmail())? user.getEmail() : oldUser.getEmail());
        update.set("sex", StringUtils.isNotBlank(user.getSex())? user.getSex() : oldUser.getSex());
        update.set("address", StringUtils.isNotBlank(user.getAddress())? user.getAddress() : oldUser.getAddress());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(new Date(System.currentTimeMillis()));
        update.set("updateDate", format);
        // 更新
        try {
            mongoTemplate.upsert(Query.query(Criteria.where("_id").is(id)), update, dbName);
            return "更新成功";
        }catch (Exception e){
            return "更新失败";
        }
    }

    @Override
    public String getUserByCondition(Map data) {
        // 获取动态的条件列表
        List list = new ArrayList();
        for (Object o : data.keySet()) {
            list.add(o);
        }


        // 构建条件对象
        List criteriaList = new ArrayList<>();
        for (int i=0; i users = mongoTemplate.find(query, User.class, dbName);
            return JSON.toJSON(users).toString();
        } catch (Exception e){
            System.out.println(e.getMessage());
            return "模糊条件查询失败!";
        }
    }


}

4.编写一个简单增删改查类(这里使用mongorepository操作)

使用repository很简单,只需要添加一个继承了MongoRepository的类,指定范型,然后将上面代码中的所有mongoTemplate换成该Repository的类即可

创建repository类示例:



import org.example.mongodemo.domain.User;
import org.springframework.data.mongodb.repository.MongoRepository;
 

public interface UserRepository extends MongoRepository {

}

你可能感兴趣的:(学习笔记,mongodb,学习,笔记)