SpringBoot中怎么对MongoDB 进行增删改查操作
发表于:2024-09-21 作者:千家信息网编辑
千家信息网最后更新 2024年09月21日,SpringBoot中怎么对MongoDB 进行增删改查操作,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。引入MongoDB
千家信息网最后更新 2024年09月21日SpringBoot中怎么对MongoDB 进行增删改查操作
SpringBoot中怎么对MongoDB 进行增删改查操作,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
引入MongoDB
4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.2.RELEASE com.kailo kailo-mongodb 0.0.1-SNAPSHOT kailo-mongodb MongoDB 1.8 org.springframework.boot spring-boot-starter org.projectlombok lombok true 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.3.2.RELEASE com.alibaba fastjson 1.2.61 org.springframework.boot spring-boot-maven-plugin
添加配置文件:application.properties
server.port=8080spring.data.mongodb.uri=mongodb://127.0.0.1:27017/xxx#spring.data.mongodb.host=127.0.0.1#spring.data.mongodb.port=27017#spring.data.mongodb.database=xxx# 默认没有账号密码#spring.data.mongodb.username=#spring.data.mongodb.password=
增删改查代码:ProductController
@Log4j2@RequestMapping("/product")@RestControllerpublic class ProductController { private final ProductRepository productRepository; private final MongoTemplate mongoTemplate; @Autowired public ProductController(ProductRepository productRepository, MongoTemplate mongoTemplate) { this.productRepository = productRepository; this.mongoTemplate = mongoTemplate; } // 增 @PostMapping("save") public ResponseEntity> save(Product product) { if (!StringUtils.isEmpty(product.get_id())) { return ResultUtils.error(); } productRepository.save(product); return ResultUtils.ok(product); } // 删 单个删除 @GetMapping("deleteById") public ResponseEntity > deleteById(String id) { if (StringUtils.isEmpty(id)) { return ResultUtils.error(); } productRepository.deleteById(id); return ResultUtils.ok(); } // 删 批量删除 @DeleteMapping("deleteByIds") public ResponseEntity > deleteByIds(@RequestBody String[] ids) { if (ids == null) { return ResultUtils.error(); } List idList = Arrays.asList(ids); Iterable deleteProducts = productRepository.findAllById((Iterable ) idList.iterator()); productRepository.deleteAll(deleteProducts); return ResultUtils.ok(); } // 改 单个 @PostMapping("update") public ResponseEntity > update(Product product) { if (StringUtils.isEmpty(product.get_id())) { return ResultUtils.error(); } product = productRepository.save(product); return ResultUtils.ok(product, "更新成功"); } // 查 查单个 @GetMapping("findById") public ResponseEntity > findById(String id) { Product product = productRepository.findById(id).get(); return ResultUtils.ok(product); } // 查 查全部列表 @GetMapping("findAll") public ResponseEntity >> findAll() { List products = productRepository.findAll(); return ResultUtils.ok(products); } // 查 分页查询 @GetMapping("findPage") public ResponseEntity >> findPage(int page, int size) { PageRequest pageRequest = PageRequest.of(page, size, Sort.unsorted()); Page productPage = productRepository.findAll(pageRequest); log.error(productPage.getClass()); log.error(productPage.getPageable().getClass()); return ResultUtils.ok(Pagination.from(productPage)); } // 查 模糊查询 @GetMapping("findByNameLike") public ResponseEntity >> findByNameLike(String name) { List products = null; if (StringUtils.isEmpty(name)) { products = productRepository.findAll(); } else { products = productRepository.findByNameLike(name); } return ResultUtils.ok(products); } @GetMapping("findPageByNameMongoTemplate") public ResponseEntity >> findPageByNameMongoTemplate(int page, int size, String name) { Query query = new Query(); query.addCriteria(Criteria.where("name").regex(name)); List products = mongoTemplate.find(query, Product.class); return ResultUtils.ok(products); } // 查 根据条件过滤 @GetMapping("findPageByNameLike") public ResponseEntity >> findPageByNameLike(int page, int size, String name) { if (StringUtils.isEmpty(name)) { return ResultUtils.error(); } PageRequest pageRequest = PageRequest.of(page, size, Sort.unsorted()); Query query = new Query(); query.addCriteria(Criteria.where("name").regex(name)); List products = mongoTemplate.find(query, Product.class); long total = mongoTemplate.count(query, Product.class); return ResultUtils.ok(Pagination.build(products, total, pageRequest)); }}
相关代码
@Data@Document(value = "xxx")public class Product implements Serializable { @Id @JSONField(name="_id") // fastjson 会过滤 _ private String _id; @Field private String name; @Field private String user; @Field private Double ccc;}
public interface ProductRepository extends MongoRepository{ List findByNameLike(String name);}
分页相关:不用自带的Page,自定义Pagination,解决序列化和反序列化问题
@Datapublic class Paginationimplements Serializable { private long total; private List content = new ArrayList(); private PaginationRequest pageable; public Pagination() { } public long getTotal() { return this.total; } /** * 根据Page,转化成 Pagination * * @param page * @param * @return */ public static Pagination from(Page page) { if (page == null) { return new Pagination<>(); } return build(page.getContent(), page.getTotalElements(), page.getPageable()); } /** * 根据参数,初始化 Pagination * * @param content * @param totalElements * @param pageable * @param * @return */ public static Pagination build(List content, long totalElements, Pageable pageable) { Pagination pageResult = new Pagination<>(); pageResult.setTotal(totalElements); pageResult.setContent(content); pageResult.setPageable(PaginationRequest.from(pageable)); return pageResult; } public int getTotalPages() { return this.getSize() == 0 ? 1 : (int) Math.ceil((double) this.total / (double) this.getSize()); } public long getTotalElements() { return this.total; } public boolean hasNext() { return this.getNumber() + 1 < this.getTotalPages(); } public int getNumber() { return this.pageable.getPageNumber(); } public int getSize() { return this.pageable.getPageSize(); } public int getNumberOfElements() { return this.content.size(); } public boolean hasPrevious() { return this.getNumber() > 0; } public boolean isFirst() { return !this.hasPrevious(); } public boolean isLast() { return !this.hasNext(); } public PaginationRequest nextPageable() { return this.hasNext() ? this.pageable.next() : null; } public PaginationRequest previousPageable() { return this.hasPrevious() ? this.pageable.previousOrFirst() : null; } public boolean hasContent() { return !this.content.isEmpty(); } public List getContent() { return Collections.unmodifiableList(this.content); } public Iterator iterator() { return this.content.iterator(); }}
@Datapublic class PaginationRequest implements Serializable { private int page; private int size; public PaginationRequest() {} public PaginationRequest(int page, int size) { this.page = page; this.size = size; } public static PaginationRequest from(Pageable pageable) { Sort sort = pageable.getSort(); return new PaginationRequest(pageable.getPageNumber(), pageable.getPageSize() ); } public PaginationRequest next() { return new PaginationRequest(this.getPageNumber() + 1, this.getPageSize()); } public PaginationRequest previous() { return this.getPageNumber() == 0 ? this : new PaginationRequest(this.getPageNumber() - 1, this.getPageSize()); } public PaginationRequest first() { return new PaginationRequest(0, this.getPageSize()); } public int getPageSize() { return this.size; } public int getPageNumber() { return this.page; } public long getOffset() { return (long)this.page * (long)this.size; } public boolean hasPrevious() { return this.page > 0; } public PaginationRequest previousOrFirst() { return this.hasPrevious() ? this.previous() : this.first(); }}
@Datapublic class Resultimplements Serializable { private int code; private String message; private T data; private long timestamp = Date.from(Instant.now()).getTime();}
@Datapublic class ResultUtils implements Serializable { public static final int SUCCESS = 200; public static final int NOT_FOUND = 404; public static final int ERROR = 500; public static final String OPT_SUCCESS_LANG = "操作成功"; public static final String OPT_ERROR_LANG = "操作失败"; public staticResponseEntity > ok() { return ok(OPT_SUCCESS_LANG); } public static ResponseEntity > ok(String message) { return ok(null, message); } public static ResponseEntity > ok(T data) { return ok(data, null); } public static ResponseEntity > ok(T data, String message) { Result result = new Result<>(); result.setCode(SUCCESS); result.setMessage(message); result.setData(data); return ResponseEntity.ok(result); } public static ResponseEntity > error() { return ok(OPT_ERROR_LANG); } public static ResponseEntity > error(String message) { return ok(null, message); } public static ResponseEntity > error(T data) { return ok(data, null); } public static ResponseEntity > error(T data, String message) { Result result = new Result<>(); result.setCode(ERROR); result.setMessage(message); result.setData(data); return ResponseEntity.ok(result); }}
关于SpringBoot中怎么对MongoDB 进行增删改查操作问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。
问题
单个
成功
代码
序列
更多
帮助
查询
解答
易行
简单易行
不用
内容
参数
密码
小伙
小伙伴
文件
方法
条件
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
软件开发企业资质证书有哪些
我的世界2b2t服务器最新版地址
企业网络安全论文研究方法
服务器4大件
地面互动投影系统软件开发
数据库系统三级模式的优缺点
软件开发应用桌面云
众神争霸服务器
网络安全攻防 致辞
关闭服务器远程桌面端口
站群服务器可以做亚马逊测评吗
路云天网络安全研究院上市股票
网络技术子网划分课件
如流服务器处理失败
进行实名制数据库横向互联
网络安全咨询顾问挣多吗
吉林网络安全知识
100T的服务器
网络安全监督自查工作
rust怎么选择日本服务器
传智互联网科技公司
网络安全家长会主题
时间服务器选择
云服务器崩溃了怎么办
路云天网络安全研究院上市股票
易汇服务器
韩国IBM服务器
虚拟服务器怎么安装安全产品
洛阳警方网络安全
2015网络安全知识试题