创建mongodb项目

首先新建一个springboot项目,新建项目略,不会的新手可以参考这里。 新建项目后目录结构如下图
创建mongodb项目_第1张图片
接下来把各个代码贴一下
控制层

package com.yulisao.controller;

import com.yulisao.dto.PageParam;
import com.yulisao.entity.TUser;
import com.yulisao.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * author yulisao
 * createDate 2023/5/31
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private TUserService userService;

    @PostMapping("/save")
    public TUser saveUser(@RequestBody TUser user) {
        return userService.saveUser(user);
    }

    @GetMapping("/findAll")
    public List<TUser> findAll() {
        return userService.findAll();
    }

    @PostMapping("/find")
    public List<TUser> findAllByCondition(@RequestBody TUser user, Date startDate, Date endDate) {
        return userService.findAllByCondition(user, startDate, endDate);
    }

    @PostMapping("/page")
    public Page<TUser> page(@RequestBody @Valid PageParam<TUser> param) {
        return userService.page(param);
    }

    @PostMapping("/count")
    public Long count(@RequestBody TUser user) {
        return userService.count(user);
    }

    @GetMapping("/{id}")
    public TUser findOne(@PathVariable("id") String id) {
        return userService.getUserById(id);
    }

    @GetMapping("/{name}")
    public TUser findOneByName(@PathVariable("name") String name) {
        return userService.getUserByName(name);
    }

    @PostMapping("/update")
    public Long update(@RequestBody TUser user) {
        return userService.updateUser(user);
    }

    @PostMapping("/updateBatch")
    public Long updateBatch(@RequestBody TUser user, String name) {
        return userService.batchUpdateUserByName(user, name);
    }

    @DeleteMapping("/delOne")
    public String delOne(@RequestBody TUser user) {
        return userService.deleteUser(user);
    }

    @DeleteMapping("/{id}")
    public String delById(@PathVariable("id") String id) {
        return userService.deleteUserById(id);
    }

}

repository接口层(这里的repository层我没有使用, 因为与下面的service层二选其一就行了。它两的区别跟 mybatis和jpa类似。)

package com.yulisao.repository;

import com.yulisao.entity.TUser;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

import java.util.Date;
import java.util.List;

public interface TUserRepository extends MongoRepository<TUser, ObjectId> {
    // MongoRepository 里面有findAll、insert等常用方法,继承之后可以直接使用,
    // 和mybatis-plus一样,只需要新建一个这样接口继承一下就好





    // 同时,如果你需要自定义查询, 就用可以用注解的形式,自己传参。 跟 Hibernate jpa 类似
    @Query("{ 'name':?0}") // 根据姓名查询
    TUser getUserByCondition(String name);

    @Query("{'Criteria.objectId' :{ $in: ?0},{'Criteria.createTime' : { $lt: ?1, $gt: ?2 }},{$limit :?3}")
    List<TUser> findListByCondition(List<String> ids, Date begin, Date end, int limit);

}

service接口层

package com.yulisao.service;

import com.yulisao.dto.PageParam;
import com.yulisao.entity.TUser;
import org.springframework.data.domain.Page;

import java.util.Date;
import java.util.List;

/**
 * author yulisao
 * createDate 2023/5/31
 */
public interface TUserService {

    /**
     * 新增
     * @param user
     * @return
     */
    TUser saveUser(TUser user);

    /**
     * 查询所有
     */
    List<TUser> findAll();

    /**
     * 根据条件 查询所有
     * @param user
     * @return
     */
    List<TUser> findAllByCondition(TUser user, Date startDate, Date endDate);

    /**
     * 根据条件 分页查询
     *
     * @param pageParam
     * @return
     */
    Page<TUser> page(PageParam<TUser> pageParam);

    /**
     * 根据条件 查询数量
     * @param user
     * @return
     */
    Long count(TUser user);


    /***
     * 根据id查询
     */
    TUser getUserById(String id);

    /**
     * 根据名称查询
     */
    TUser getUserByName(String name);

    /**
     * 更新对象
     */
    Long updateUser(TUser user);

    /**
     * 根据姓名批量更新对象
     */
    Long batchUpdateUserByName(TUser user, String name);

    /***
     * 删除对象
     */
    String deleteUser(TUser user);

    /**
     * 根据id删除
     */
    String deleteUserById(String id);

}

service实现层

package com.yulisao.service.impl;

import com.yulisao.dto.PageParam;
import com.yulisao.entity.TUser;
import com.yulisao.service.TUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
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 com.mongodb.client.result.UpdateResult;

import java.util.Date;
import java.util.List;

/**
 * author yulisao
 * createDate 2023/5/31
 */
public class TUserServiceImpl implements TUserService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public TUser saveUser(TUser user) {
        return mongoTemplate.save(user); // or insert
    }

    @Override
    public List<TUser> findAll() {
        return mongoTemplate.findAll(TUser.class);
    }

    @Override
    public List<TUser> findAllByCondition(TUser user, Date startDate, Date endDate) {
        Criteria cri = new Criteria();
        cri.andOperator(Criteria.where("createTime").gte(startDate), Criteria.where("createTime").lt(endDate));
        if (StringUtils.isNotBlank(user.getName())) {
            cri.and("name").is(user.getName());
        }
        if (user.getAge() != null) {
            cri.and("age").is(user.getAge());
        }
        // cri.and("userType").in("P", "U");
        //more...

        return mongoTemplate.find(new Query(cri).with(Sort.by(Sort.Direction.DESC,"age")), TUser.class);
    }

    @Override
    public Page<TUser> page(PageParam<TUser> pageParam) {
        int currentPage = pageParam.getCurrentPage();
        int pageSize = pageParam.getPageSize();
        TUser param = pageParam.getParam(); // 搜索条件

        Query query = new Query();
        /*
        // 这里的搜索条件根据自己需要写,和下面的count方法保持一致!
        // Criteria 和 Query 里面的方法有很多,可以自己点击进去看看,以下是几个示例
        query.addCriteria(Criteria.where("name").regex("^w")); // 姓名以w结尾
        Pattern pattern = Pattern.compile(String.format("%s%s%s", "^.*", "张", ".*$"), Pattern.CASE_INSENSITIVE);
        query.addCriteria(Criteria.where("username").regex(pattern)); // 模糊查询 含有“张”的记录
        query.addCriteria(Criteria.where("age").lt("35").gt("20")); // 年纪在20-30之间*
        query.with(Sort.by(Sort.Direction.DESC,"age")); // 根据年纪倒叙 新版本已不支持 new Sort() 的写法了
        */

        // 分页 && 排序
        //PageRequest pageable = new PageRequest(currentPage, pageSize, Sort.Direction.DESC, "username"); // 新版本已不支持 new PageRequest() 的写法了
        Pageable pageable = PageRequest.of(currentPage, pageSize, Sort.Direction.DESC, "age");
        query.with(pageable);

        long count = count(param); // 查询符合条件的总条数
        if (count > 0) {
            List<TUser> list = mongoTemplate.find(query, TUser.class); // 分页查询
            return new PageImpl<>(list, pageable, count);
        }

        return null;
    }

    @Override
    public Long count(TUser user) {
        Criteria cri = new Criteria();
        if (StringUtils.isNotBlank(user.getName())) {
            cri.and("name").is(user.getName());
        }
        if (user.getAge() != null) {
            cri.and("age").is(user.getAge());
        }
        //more...

        return mongoTemplate.count(new Query(cri), TUser.class);
    }

    @Override
    public TUser getUserById(String id) {
        Query query = new Query(Criteria.where("objectId").is(id));
        return mongoTemplate.findOne(query, TUser.class);
    }

    @Override
    public TUser getUserByName(String name) {
        Query query = new Query(Criteria.where("name").is(name));
        return mongoTemplate.findOne(query, TUser.class);
    }

    @Override
    public Long updateUser(TUser user) {
        Query query = new Query(Criteria.where("objectId").is(user.getObjectId()));

        Update update = new Update();
        update.set("name", user.getName());
        update.set("age", user.getAge());
        update.set("updateTime", new Date());

        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, TUser.class);
        return updateResult.getModifiedCount();
    }

    @Override
    public Long batchUpdateUserByName(TUser user, String name) {
        Query query = new Query(Criteria.where("name").is(name));

        Update update = new Update();
        update.set("name", user.getName());
        update.set("age", user.getAge());
        update.set("updateTime", new Date());

        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, TUser.class);
        return updateResult.getModifiedCount();
    }

    @Override
    public String deleteUser(TUser user) {
        mongoTemplate.remove(user);
        return "success";
    }

    @Override
    public String deleteUserById(String id) {
        TUser user = getUserById(id);
        deleteUser(user);
        return "success";
    }

}

实体对象

package com.yulisao.entity;

import lombok.Data;
import lombok.ToString;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.util.Date;

/**
 * author yulisao
 * createDate 2023/5/31
 */
@Data
@ToString
@Document(collection = "t_user") // 声明是mongdb文档,相当于@tableName注解
public class TUser {

    @Id
    private String objectId; // 文档的唯一标识,自带索引,在mongodb中为ObjectId,类似mysql表的主键id。通过时间戳+机器标识+进程ID+自增计数器构成

    @Field("name")
    private String name;

    @Field("age")
    private Integer age;

    @Field("create_time") // 映射 mongodb中的字段名,可以不加,不加的话默认以key为列名, 也就是createTime为列名 。
    private Date createTime;

    @Field("update_time")
    private Date updateTime;

    /**
     * 其他可能用到注解
     * @Transient 表示这个是文档表里面不存在的字段,虚拟字段
     * @Indexed 表示给这个字段添加索引。 有索引查询会快很多
     * @CompoundIndex 表示给这个字段添加复合索引。
     */
}

分页请求对象

package com.yulisao.dto;

import java.io.Serializable;

public class PageParam<T> implements Serializable {

	private static final long serialVersionUID = 1L;
	private Integer currentPage;
	private Integer pageSize;
	private T param;

	public int getCurrentPage() {
		return (currentPage == null || currentPage <= 0) ? 1 : currentPage;
	}

	public PageParam<T> setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
		return this;
	}

	public int getPageSize() {
		return (pageSize == null || pageSize <= 0) ? 10 : pageSize;
	}

	public PageParam<T> setPageSize(int pageSize) {
		this.pageSize = pageSize;
		return this;
	}

	public T getParam() {
		return param;
	}

	public PageParam<T> setParam(T param) {
		this.param = param;
		return this;
	}

}

启动类

package com.yulisao;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 项目启动类
 * author yulisao
 * createDate 2023/05/31
 */
@SpringBootApplication  
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


pom文件支持

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yulisao</groupId>
    <artifactId>mydemo</artifactId>
    <packaging>war</packaging>
    <version>1.0.0-SNAPSHOT</version>

    <!-- springboot依赖支持 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>
 
</project>

关于mongdb的spring官方文档地址: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/,有兴趣的可以去了解。

刚创建好springboot项目的时候就一个启动类。此时如果启动报错Cannot determine embedded database driver class for database type NONE 这是因为创建了数据库连接池却连不上数据库报错,可以在启动类上加@EnableAutoConfiguration注解排除掉数据源

@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,DataSourceTransactionManagerAutoConfiguration.class, MybatisAutoConfiguration.class}) // 排除默认的数据源

你可能感兴趣的:(SQL,java,SpingBoot,mongodb,java,spring)