introduction:
There are many common data repositories, such as the common Mysql, Redis, and PostgreSql. But in the current era of agile development, MongoDB does not need to design the database structure, and eliminates design steps. When scaling, it supports horizontal scaling, and directly adds new server storage nodes, allowing the system to easily adapt to large-scale data and high-concurrency access. Also supports index structure. After reading the following article, there are straightforward examples and practical cases. You can directly Ctrl C+V and port it to your own code. In addition, the examples are rich in comments. As long as you spend some time reading, you will understand and quickly get started. Then I will tell you about it below.
MongoDB form:
MongoDB is a non-relational database based on Json data structures. Each Json document has a unique primary key.
1. To integrate MongoDB in SpringBoot project, you need to first introduce Pom file dependencies:
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
2. Configure in the yaml configuration file. Spring will automatically scan the configuration file and use it.
spring: data: mongodb: uri: mongodb://username:password@ip:port/dataBaseName # username、password、ip、port、dataBaseNameYou need to write your own name
3. In terms of use, we define a Service class, which encapsulates Mongo operations. Here we open this Mongo Service to everyone for convenience:
//Use generic argument transfer to effectively make the code structure clear and the code can be reused. In addition, the addition, deletion, modification and search operations here are all in the case of adding transactions.@Service public class BaseService<T, ID> { private MongoTemplate mongoTemplate; private MongoClient client; @Resource public void setClient(MongoClient client) { = client; } @Resource public void setMongoTemplate(MongoTemplate mongoTemplate) { = mongoTemplate; } /** * MongoDB transactions manage data consistency. Failed rollback operation involved * @param entity Add data * @param <S> Data Type * @return Added data */ public <S extends T> S insert(S entity) { ClientSession clientSession = (); try { //Start a transaction (); return (entity); } catch (Exception e) { //rollback (); throw new BadRequestException(()); }finally { // The session must be ended regardless of whether an exception occurs or not. Free up resources (); } } /** * Primary key deletion * * @param s Delete data * @param id Primary key id * @param <S> Delete data type * @return Delete the result */ public <S extends T> DeleteResult deleteById(S s, ID id) { ClientSession clientSession = (); try { (); Query query = (("_id").is(id)); return (query, ()); } catch (Exception e) { (); throw new BadRequestException(()); } } /** * Batch deletion * * @param s Delete data * @param ids primary key id * @param <S> Delete data type * @return Delete the result */ public <S extends T> DeleteResult deleteByIds(S s, List<ID> ids) { ClientSession clientSession = (); try { (); Query query = (("_id").in(ids)); return (query, ()); } catch (Exception e) { (); throw new BadRequestException(()); } } /** * Revise * * @param s Modify data * @param id Primary key id * @param <S> Modify the data type * @return Modify result */ public <S extends T> UpdateResult update(S s, String id) { ClientSession clientSession = (); try { (); Query query = (("_id").is(id)); Update update = new Update(); Field[] fields = ().getDeclaredFields(); for (Field field : fields) { (true); //Get attribute String name = (); //Get the attribute value Object value = (s); if ((value)) { (name, value); } } return (query, update, ()); } catch (Exception e) { (); throw new BadRequestException(()); } } /** *Batch modification according to conditions * * @param s Modify data * @param query Modify the condition * @param update Modify content * @param <S> Modify the data type * @return Modify result */ public <S extends T> UpdateResult updateByQuery(S s, Query query, Update update) { ClientSession clientSession = (); try { (); return (query, update, ()); } catch (Exception e) { (); throw new BadRequestException(()); } } /** * Pagination query * * @param dto Query Conditions * @param s Result Type * @param orderName Sort fields * @param <S> Type * @return Pagination data */ public <S extends T> PageVO pagination(PageRequestDTO dto, S s, String orderName, String orderRules) { return (dto, (), mongoTemplate, orderName, orderRules); } /** * Query data details based on table id * * @param id Table id * @param s Data type * @param <S> Returns the data type * @return Details */ public <S extends T> S getInfoById(ID id, S s) { return (S) (id, ()); } /** * Query information based on multiple tables * * @param ids Multiple table ids * @param s Data type * @param <S>Return data type * @return Details Collection */ public <S extends T> List<S> getInfoByIds(List<ID> ids, S s) { Query query = (("_id").in(ids)); return (List<S>) (query, ()); } /** * Conditional query * * @param query query conditions * @param s Return result * @param <S> Result Type * @return list */ public <S extends T> List<S> listByQuery(Query query, S s) { if (null != query) { return (List<S>) (query, ()); } return (List<S>) (()); } }
4. Then inherit this Service class in the business class you want to use Mongo, like this:
@Service @Slf4j public class ****ServiceImpl extends BaseService<****Entity, String> implements ****Service { /** * Business code */ }
Similar to using Mybatis-Plus, to use the Service hierarchy method in MP, you need to inherit ServiceImpl<Mapper, Entity>, like this:
@Service @Slf4j public class ****ServiceImpl extends ServiceImpl<****Mapper, ****Entity> implements *****Service { /** * Business code */ }
5. How to use it in business categories? I will give some examples here to illustrate it to help everyone understand it to the greatest extent and can quickly get started.
Query and Criteria:
Criteria is used to build query conditions, similar to wrapper in Mybatis-Plus. Query is used to combine one or more Criterias.
When building multi-condition query, use the following statement to merge. There are two cases of merging. One is that criteria is built based on where, and the other is built from and:
Query query = new Query(); Criteria criteria1 = ("_id").is(id); (criteria1);//where formCriteria criteria2 = new Criteria(); ("_id").is(id);//and form(criteria2);
where is a single condition query, and can build queries containing multiple conditions.
When using it, like Mybatis-Plus, you need to operate on the entity class. Use the @Id annotation to specify the primary key Id, and use the @Collation annotation to specify the name of the entity class.
Like this:
import ; import ; import ; import ; @Data @Collation("taskLog") public class TaskLog implements Serializable { @Id private String logId; /* * Other properties */ }
increase:
@Service @Slf4j public class TaskLogServiceImpl extends BaseService<TaskLog, String> implements TaskLogService { @Autowired private MongoTemplate mongoTemplate; //Add one @Override public void save(TaskLog tasklog) { (tasklog);//Actually call the save method in mongoTemplate } //Batch increase public void insertMany(List<TaskLog> tasklogs) { (tasklogs, ); } } /** * The difference between insert and save in mongoTemplate: * insert() method: If the primary key id in tasklog already exists, an exception will be thrown, indicating that a duplicate primary key has been inserted. If the primary key does not exist, it will be generated normally. * Used to generate new data * * save() method: If the primary key id already exists, the original data will be overwritten. * Used to update data */
delete:
@Service @Slf4j public class TaskLogServiceImpl extends BaseService<TaskLog, String> implements TaskLogService { //Delete a based on the primary key id @Override public void delete(String logId) { (new TaskLog(), logId); } //Batch delete according to the primary key id public void deleteMany(List<String> logIds) { (new TaskLog(), logIds); } } /** * The actual use is the remove() method of mongoTemplate. * Query query = (("_id").is(id)); * (query, ()); * * Query query = (("_id").in(ids)); * (query, ()); */
change:
@Service @Slf4j public class TaskLogServiceImpl extends BaseService<TaskLog, String> implements TaskLogService { //Modify according to the primary key id @Override public void update(String logId) { (data, ()); } } /** * The actual use is the updateFirst() method in mongoTemplate * Query query = (("_id").is(id)); * Update update = new Update(); * Field[] fields = ().getDeclaredFields(); * for (Field field : fields) { * (true); * //Get attributes * String name = (); * //Get attribute value * Object value = (s); * if ((value)) { * (name, value); * } * } * Use reflection to overwrite each field and field value in the corresponding entity class. * (query, update, ()); */
Simple check:
@Service @Slf4j public class AnalysisStudyServiceImpl extends BaseService<AnalysisStudy, String> implements AnalysisStudyService { private MongoTemplate mongoTemplate; @Resource public void setMongoTemplate(MongoTemplate mongoTemplate) { = mongoTemplate; } /** * Conditional query */ @Override public void find(String patientId, String hospitalId) { Query query = (("patientId").is(patientId).and("hospitalId").is(hospitalId)); List<AnalysisStudy> analysisStudyList = (query, new AnalysisStudy()); } //The underlying layer uses the find() method of mongoTemplate to query data that meets the query conditions. //If the built query is null, listByQuery() will call findAll() method to query all data}
Pagination query (key points):
@Service @Slf4j public class AnalysisStudyServiceImpl extends BaseService<AnalysisStudy, String> implements AnalysisStudyService { @Override public PageVO<AnalysisStudy> queryPage(PageRequestDTO pageRequest) { return (pageRequest, new AnalysisStudy(), "studyDateTime", "asc"); //The first parameter: query conditions //The second parameter: result type //The third parameter: sort field //The fourth parameter: sort type, ascending ASC or descending DESC } } // Method of encapsulation in BaseServicepublic <S extends T> PageVO pagination(PageRequestDTO dto, S s, String orderName, String orderRules) { return (dto, (), mongoTemplate, orderName, orderRules); }
//The use of pagination query is encapsulated into a tool class@Slf4j public class DataToolUtil { //Prevent tool classes from being instantiated private DataToolUtil() { throw new IllegalStateException("Utility class"); } /** * In mongodb, the number of results and query results are encapsulated through PageVO objects. * * @param dto paging conditions * @param tClass Returns the data type * @param mongoTemplate query template * @param <T> Return data * @param orderName Sort column name * @param orderRules sorting rules asc positive order desc reverse order * @return Pagination results */ public static <T> PageVO<T> pagination(PageRequestDTO dto, Class<T> tClass, MongoTemplate mongoTemplate, String orderName, String orderRules) { Query query = handParam(dto); if (!(())) {//The page number without requests is the first page by default (0); } if (!(())) {//There is no display number per page, the default is 10 displays (10); } //Calculate the number of documents using the given query object query long count = (query, tClass); /** * (): Page number requested by the user * (): Number of displayed per page * offset is used to calculate offset * For example, the user requests page 2, (2-1)=1. 10 displays per page, 1*10=10. Then displays starting from the 11th. */ int offset = (() - 1) * (); if ((orderName) && (orderRules)) { String asc = "asc";//Sorting ascending order String desc = "desc";//Sorting in descending order if ((orderRules)) { //Sorting logic (((orderName))); } if ((orderRules)) { //Sorting logic (((orderName))); } } // Pagination logic /** * For example: Skip 10, get 10 per page, displaying 11~20 data. */ (offset).limit(()); ("querySql>>>>" + query); //find() is used to get a list of documents that meet the query query criteria.tClass is the target entity class List<T> list = (query, tClass); //Create an object to encapsulate the results of paging query PageVO<T> pageDTO = new PageVO<>(); //Set the number of query satisfying conditions for the PageVO object. (count); //Set the query result into the PageVO object. (list); return pageDTO; } /** * Dynamic query of MongoDB database based on incoming query conditions * @param dto * @return */ private static Query handParam(PageRequestDTO dto) { Query query = new Query();//Create a MongoDB query object List<ParamDTO> params = ();//Get the query condition list of incoming parameters Criteria criteria = new Criteria();//Create MongoDB's Criteria object to build query conditions (param -> {//Travel the query condition list String operator = (); switch (operator) { //This statement constructs a query condition equal to (eq), and uses the is method to specify that the field is equal to the given value. case "eq" -> (()).is(()); //regex means using regular expressions to query, () to construct a regular expression. This regular expression is '^.*value.*$' //'^' and '$' are the start and end identifiers of regular expressions. ‘.* means matching characters 0 or more times’ //Pattern.CASE_INSENSITIVE means case insensitive case "like" -> (()).regex(("^.*" + () + ".*$", Pattern.CASE_INSENSITIVE)); case "le" -> (()).lt(()); case "ge" -> (()).gt(()); //Convert to String type list of strings case "in" -> { List<String> values = (().toString(), ); (()).in(values); } case "between" -> { if (() instanceof JSONArray) { List<Object> list = (().toString(), ); if ((list)) { //gte: greater than or equal to //lte: less than or equal to (()).gte((0)).lte((1)); } } } default -> {//No case statement is matched, default statement is executed by default. } } }); (criteria);//Add the built Criteria object to the query object. return query; } }
@Data public class PageVO<T> { private Long totalNum;//Total results private List<T>results;//Query results}
@Data @Schema(description = "Pagination query criteria") public class PageRequestDTO { @Schema(description = "Current page count") private Integer currentPageNum; @Schema(description = "Display row count") private Integer size; @Schema(description = "Query Conditions") private List<ParamDTO> params; }
This is the article about how MongoDB is used in Spring Boot. For more information about MongoDB Spring Boot, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!