Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to add, delete, modify and check MongoDB in SpringBoot

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

How to add, delete, modify and search MongoDB in SpringBoot? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Introduction of 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

Add profile: 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# does not have an account password by default # spring.data.mongodb.username=#spring.data.mongodb.password=

Add, delete, modify and check code: 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;} / / add @ PostMapping ("save") public ResponseEntity save (Product product) {if (! StringUtils.isEmpty (product.get_id () {return ResultUtils.error () } productRepository.save (product); return ResultUtils.ok (product);} / / single deletion @ GetMapping ("deleteById") public ResponseEntity deleteById (String id) {if (StringUtils.isEmpty (id)) {return ResultUtils.error ();} productRepository.deleteById (id); return ResultUtils.ok () } / / delete @ 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 () } / / change a single @ PostMapping ("update") public ResponseEntity update (Product product) {if (StringUtils.isEmpty (product.get_id () {return ResultUtils.error ();} product = productRepository.save (product); return ResultUtils.ok (product, "updated successfully") } / / check a single @ GetMapping ("findById") public ResponseEntity findById (String id) {Product product = productRepository.findById (id). Get (); return ResultUtils.ok (product);} / / check all lists @ GetMapping ("findAll") public ResponseEntity findAll () {List products = productRepository.findAll (); return ResultUtils.ok (products) } / / check paging query @ 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)) } / / check fuzzy query @ 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) } / / filter @ 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 (products, total, pageRequest);}}

Related code

@ Data@Document (value = "xxx") public class Product implements Serializable {@ Id @ JSONField (name= "_ id") / / fastjson filters _ private String _ id; @ Field private String name; @ Field private String user; @ Field private Double ccc;} public interface ProductRepository extends MongoRepository {List findByNameLike (String name);}

Paging related: do not need your own Page, custom Pagination to solve serialization and deserialization problems

@ Datapublic class Pagination implements Serializable {private long total; private List content = new ArrayList (); private PaginationRequest pageable; public Pagination () {} public long getTotal () {return this.total } / * according to Page, convert to 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 ()) Initialize 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)) according to the parameters 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 Result implements 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 = "Operation successful" Public static final String OPT_ERROR_LANG = "Operation failed"; public static ResponseEntity 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) }} the answer to the question about how to add, delete, modify and check MongoDB in SpringBoot is shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report