1: jar packages to be referenced:
<!-- mongodb Link package --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>2.3.4.RELEASE</version> </dependency>
2: This package has two classes that can manipulate the curd of the database
1: MongoRepository
2: MongoTemplate
Here is a brief description of the operation methods of the next two classes
first MongoRepository is simple, but in the operation, when some replicated queries or the dynamic addition of attributes of map need to be used, the operation is very troublesome, on the contrary MongoTemplate is much simpler.
Let's talk about the use of MongoRepository:
3: Use of MongoRepository Simple curd
In the first step, the Dao layer needs to write an interface, which is equivalent to the mapping interface in mybits If you want to use a map array, you can inherit the map class from a class. MapInfo is a custom entity. Because I want the map type, I customized a MapInfo to inherit the map object.public interface DictionaryHeaderRepository extends MongoRepository<DictionaryHeaderDO, String> { }Step 2: define an object entity class: data object layer data layer
Main: the dictionaryHeader in @ Document(collection = "dictionaryHeader") is the table name, which is user-defined
Data @Document(collection = "dictionaryHeader") public class DictionaryHeaderDO extends BaseEntity{ //pid is used internally by mongodb @Id private String id; @AutoIncKey private Long seqId;//Sequence value /** * code */ private String code; /** * Chinese name */ private String name; /** * Remarks */ private String remarks; /** * The status 0 is valid and 1 is invalid. The default is 0 */ private String logic_delete; }
Step 3: save the method and directly put the object into the method sava inherited from the previous dao layer interface without creating a table. mongo will create tables based on objects.
In addition, this method is also used for modification here. It should be noted that only the data to be modified is transmitted during modification. All other fields will be cleared. Therefore, before modifying, you must first query all the values of the entity object, then modify the object, and then call the save method. This is also the place of comparison. Such a problem will not occur with MongoTemplate.
/** * Preservation method * @param request */ @Override public int SaveInfo(StandardDetailRequest request) { //Object to data object StandardDetailDO data=new StandardDetailDO(); BeanUtils.copyProperties(request, data); StandardDetailDO count = standardInfoRepository.save(data); if (count != null) { return 1; } else { return 0; } }
The fourth step: query method: in fact, it is called the findAll method in the inheritance interface of dao. The trouble here is to query by conditions. There are many pits. Therefore, the MongoTemplate class operation is selected.
@Override public List<DictionaryHeaderDTO> GetHeaderList(int current, int rowCount, String sortId) { List<DictionaryHeaderDTO> lists = new ArrayList<>(); List<DictionaryHeaderDO> all=dictionaryHeaderRepository.findAll(); lists= all.stream() .map(a -> { DictionaryHeaderDTO dto = new DictionaryHeaderDTO(); BeanUtils.copyProperties(a, dto); return dto; }) .collect(Collectors.toList()); return lists; }Step 5: delete According to the above method, you can directly call delete to delete a specific object. If the parameter is an object, you can also delete all.
summary MongoRepository is not suitable for curd, but since MongoRepository exists, it makes sense. First of all, it is very simple and easy to use. It mainly has other easy-to-use methods, such as checking the total number of pages, whether the data exists, and so on.
4: Use of MongoTemplate
He doesn't need to use interfaces to inherit methods in dao layer, just use annotations directly.
@Autowired MongoTemplate mongo;
Then you can curd him
Query method:
Note: collection inside_ NAME_ Attribute is a constant, and the value is the specific table name.
@Override public List<EntryAttributeDTO> QueryInfo(EntryAttributeRequest request) { //Add condition query Query query = new Query(Criteria.where("logic_delete").is("0")); if (!StringUtil.isNullOrEmpty(request.getCode())) { query.addCriteria(Criteria.where("code").is(request.getCode())); } if (!StringUtil.isNullOrEmpty(request.getName())) { query.addCriteria(Criteria.where("name").is(request.getName())); } if (!StringUtil.isNullOrEmpty(request.getId())) { query.addCriteria(Criteria.where("id").is(request.getId())); } // Data meeting all conditions List<Map> ans = mongo.find(query, Map.class, TableNameInfo.COLLECTION_NAME_ATTRIBUTE); List<EntryAttributeDTO> listDOs = MapObjectUtil.listMapParseListObj(ans, EntryAttributeDTO.class); return listDOs; }
New method:
List<SysUser> userList = new ArrayList<>(); userList.add(new SysUser(11,"1","Bai Xiaofei","18888888888")); userList.add(new SysUser(9,"1","Bai Jingting","13333333333")); userList.add(new SysUser(5,"1","Lin Yujia","14444444444")); userList.add(new SysUser(6,"1","Peng Yuyan","15555555555")); userList.add(new SysUser(7,"1","Jay Chou","16666666666")); mongoTemplate.insert(userList, "userList");
Modification method:
It can be modified according to specific fields. You don't need to query all values first, just use id.
Query query = new Query(); query.addCriteria(Criteria.where("id").is(request.getId())); Update update = new Update(); if(!StringUtil.isNullOrEmpty(request.getName())){ update.set("name", request.getName()); } if(request.getNum()!=null && request.getNum()>0){ update.set("num", request.getNum()); } if( request.getParent_Id()>0){ update.set("parent_Id", request.getParent_Id()); } if(request.getIs_disable()>0){ update.set("is_disable", request.getIs_disable()); } if(request.getLevel()>0){ update.set("level", request.getLevel()); } if(!StringUtil.isNullOrEmpty(request.getRemarks())){ update.set("remarks", request.getRemarks()); } UpdateResult result = mongo.updateFirst(query, update, ModularDO.class); if(result.getMatchedCount()>0){ count = 1; }
Delete method:
In fact, this is a logical deletion method. Is the modification effective
Query , Update is the class in the jar package. Be careful not to misquote when quoting
@Override public long deleteInfo(StandardDetailRequest req) { // Check data if(req==null){ throw new BusinessException(ResultCodeEnum.DATA_NOT_EXIST); } if(StringUtil.isNullOrEmpty(req.getId())){ throw new BusinessException(ResultCodeEnum.MISS_PARAM); } //Object to data object Query query = new Query(); query.addCriteria(Criteria.where("id").is(req.getId())); Update update = Update.update("logic_delete",req.getLogic_delete()).set("updateAt",req.getUpdateAt()).set("updateBy",req.getUpdateBy()); UpdateResult result = mongo.updateFirst(query, update, StandardDetailDO.class); return result.getMatchedCount(); } }
5: There are also some problems, such as how to do self growing columns? In fact, mongo added a new table to manage the self growing column data, and then made an annotation in java.
When adding a column attribute to an entity object, a
//Identification annotation: the identification primary key ID needs to be automatically increased @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface AutoIncKey { }
@AutoIncKey private Long seqId;//Sequence value
package com.health.standard.config.mongo; import com.health.standard.data.AutoIncKey; import com.health.standard.data.entity.SeqInfo; import com.health.standard.data.entity.StandardDetailDO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.FindAndModifyOptions; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Update; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Component; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; //@Component generally refers to a component that adds a SaveEventListener to a container @Component public class SaveEventListener extends AbstractMongoEventListener<Object>{ @Autowired MongoTemplate mongo; @Override public void onBeforeConvert(BeforeConvertEvent<Object> event) { final Object source = event.getSource(); if (source != null) { ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() { public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { ReflectionUtils.makeAccessible(field); // If our custom AutoIncKey annotation is added to the field if (field.isAnnotationPresent(AutoIncKey.class)) { // Set auto increment ID field.set(source, getNextId(source.getClass().getSimpleName())); } } }); } } private Long getNextId(String collName) { Query query = new Query(Criteria.where("collName").is(collName)); Update update = new Update(); update.inc("seqId", 1); FindAndModifyOptions options = new FindAndModifyOptions(); options.upsert(true); options.returnNew(true); SeqInfo seq = mongo .findAndModify(query, update, options, SeqInfo.class); return seq.getSeqId(); } }