Spring Boot integration --MongoDB integrated 2 (MongoDB entity and create simple CRUD)

Previous article

About Version

rely version
springboot 2.0.8.RELEASE
mongodb 4.0.14

This content just to introduce mongodb most basic use and configuration, as a well-known database, its existence a considerable number of advanced usage, start to introduce content to be large, of course, I am not the god of related fields, the following content is just finishing his Some accumulation of daily use. It is the accumulation of their own experience, but also want to help the students later

About the project

This content is what I try to finishing work in contact with the various tools used in the method in springboot. All the methods described below have been provided a test case. Because each example involves more code, so the article posted only part of the code. All code here: https: //gitee.com/daifyutils/springboot-samples.

MongoDB table (set) is defined

A type of data stored in MySQL aggregate called table (table), it is called the set (Collections) in the mongodb. The mongodb each piece of data is called a document (document).

Traditional MySQL need to create different tables ahead of schedule in the database, using Spring Boot operating mongodb time do not need to create a set of database structure, and by mongodb entity is defined as an entity to complete the creation of the collection.

Defined entities need to comment

Spring Data collection In order to define the structure of the mongodb, provides the following several annotations

annotation Explanation
@Document Identifies the current entity is an entity mongodb
@Id Identifies the current field primary key should be noted that this can only be one comment
@Indexed Identifies the current field needs to add an index, add a field after the index during query time will improve the speed
@CompoundIndex Identifies a joint index
@Field For additional contents of the current field defined primarily used to define the actual name of the collection in the field
@Transient This field identifies the property rather than as a java mongodb field
@DBRef This field associate with another document mongodb

Use annotations

Use annotations

Now create the following two entities

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.List;

@Data
@Document(collection = "Province")
@CompoundIndexes({
    @CompoundIndex(name = "userName_age_idx", def = "{'provinceName': 1, 'provinceCode': -1}")
})
public class Province {

    @Id
    private String id;

    private String provinceName;

    private String provinceCode;

    @DBRef
    private List<City> cities;
}

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

@Data
@Document(collection = "City")
public class City {

    @Id
    private String id;

    private String cityName;

    @Indexed
    @Field(value = "code")
    private String cityCode;

    @Transient
    private String cityRemark;

}

Notes the role of the example above, use:

@Document

@Document used in the above example defines the two data sets Provinceand City.

@Id

Data set Provinceand Citythe id field is defined as the primary key.

@Indexed

Data collection Cityin the field cityCode index is added.

@Field(value = “code”)

In the definition of mongodb field when not added @Fieldsaved when annotations to the collection of field names and attribute names entities are consistent, and the data set Cityin cityCode field is added after the above annotation holding on to a set of field is set tocode

@Transient

This field identifies cityRemarkonly be used as a java property, saving the data to mongodb when this content will not be saved.

@DBRef

Mongodb this field and other related documents, add annotations and do not add this major difference is that this annotation. When the notes do not add this time, this field of Citycontents as Provincesaved part of the document, and when to add this annotation Provincedocument will maintain Cityprimary key value.

When we create some Provinceand Citythe data can be seen Provincein the data as follows:

Here Insert Picture Description

@CompoundIndex

Will provinceNameand provinceCodefield as a joint index. Parameter specifies the direction of the digital index, 1 for the positive sequence, reverse -1. It should be noted in use @Indexedwhen the identity of the index, after you create a collection automatically creates a corresponding index, used @CompoundIndexto identify when the index is generated only after the new data associated with the index.

mongodb simple CRUD

Spring Data mongodb by operating mainly use two types of data manipulation tools, one is MongoTemplatethat he is mongodb data access templates provide a basis for data access interface. While the other was to create a succession MongoRepositoryof data access interface, MongoRepositorydata access interface based on JPA Rules, which provides basic CRUD operations, although they can not achieve some sophisticated statistical and associated query, but because the offers 自定义方法it for very simple operation on a single table.

Based MongoRepository of CRUD

Save & Update

MongoRepository updates are saved and the save method, and for batch processing MongoRepository provides a method saveAll

	@Override
    public void saveOne(Product product) {
        productRepository.save(product);
    }

    @Override
    public void batchSave(List<Product> products) {
        productRepository.saveAll(products);
    }

delete

MongoRepositoryAbout Removing provides is delete(实体对象)a method that needs to be passed as a parameter entity mongodb come in, many times we delete are based ID, so the deleteByIdfrequency of use will be more certain. But Delete ID-based MongoRepositorymethod does not provide batch processing, but can be used 自定义方法to create a way to achieve bulk delete deleteAllByIdIn

    @Override
    public void deleteOne(String id) {
        productRepository.deleteById(id);
    }

    @Override
    public void batchDelete(List<String> idList) {
        productRepository.deleteAllByIdIn(idList);
    }

Inquire

MongoRepositoryExample query needs with regard to use of such content will mongodb entity into a condition to filter the query, and the query needs to be paged or sort operations, need to be used to achieve Pageable and Sort data paging.

    @Override
    public List<Product> queryByEntity(Product product) {

        Example<Product> of = Example.of(product);

        List<Product> all = productRepository.findAll(of);
        return all;
    }

    @Override
    public Page<Product> pageByEntity(Product product, int page, int size) {
        Example<Product> of = Example.of(product);
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Product> all = productRepository.findAll(of, pageable);

        return all;
    }

Note that sometimes we create 自定义方法the need for paging query, this time about the content of the page does not need to make any changes in the method name, just add the parameters in the last Pageable and returns is amended as follows Page <{mongodb data entity}> this method can be paged using paging parameters and returns the data.

Based MongoTemplate of CRUD

Storage

Although many MongoTemplate query requires the user to set their own, but it also provides the basis for the query interface. For example MongoTemplate provides a save method to save the data.

    @Override
    public void saveOneByTemplate(Product product) {
        mongoTemplate.save(product);
    }

Update

MongoTemplate provides for data update upsert, updateFirst, updateMultiand other methods are based on the above methods doUpdateof implementation. Here it is necessary to provide a positioning update user data Query.

    /**
     * 执行插入。
     * @param queryProduct
     * @param product
     */
    @Override
    public void updateOneByTemplate(Product queryProduct,Product product) {
        Query query = new Query();
        Criteria criteria = Criteria.byExample(Example.of(queryProduct));
        query.addCriteria(criteria);
        Update update = new Update();
        update.set("id",product.getId());
        update.set("productName",product.getProductName());
        update.set("productMoney",product.getProductMoney());
        mongoTemplate.updateMulti(query, update,Product.class);
    }

delete

MongoTemplate provides removea method to remove it, of course, based on the delete operation is also a need to provide updated positioning data Query. MongoTemplate also provides a findAllAndRemovefind and delete interface, and of course I'm not that much in the actual development of this interface is used.

    @Override
    public void deleteOneByTemplate(String id) {
        Query query = new Query();
        Criteria criteria = Criteria.where("id").is(id);
        query.addCriteria(criteria);
        mongoTemplate.remove(query,Product.class);
    }

    @Override
    public void batchDeleteByTemplate(List<String> idList) {
        Query query = new Query();
        Criteria criteria = Criteria.where("id").in(idList);
        query.addCriteria(criteria);
        mongoTemplate.remove(query,Product.class);
    }

Inquire

MongoTemplate query is using findXXXto achieve, the core content is still Query. And the use of different MongoRepository, MongoTemplate page does not provide a simple query interface, you need to then get paged data according to the total number of first beg. Note that the paging parameters which requires Querysetting, mainly skip(initial number of rows), and limit(the number of display lines)

    @Override
    public List<Product> queryByEntityByTemplate(Product product) {
        Query query = new Query();
        Criteria criteria = Criteria.byExample(Example.of(product));
        query.addCriteria(criteria);

        List<Product> products = mongoTemplate.find(query, Product.class);
        return products;
    }

    @Override
    public Page<Product> pageByEntityByTemplate(Product product, long startNum, int size) {
        Query query = new Query();
        Criteria criteria = Criteria.byExample(Example.of(product));
        query.addCriteria(criteria);
        long count = mongoTemplate.count(query, Product.class);
        // 分页参数
        query.skip(startNum).limit(size);
        List<Product> products = mongoTemplate.find(query, Product.class);
        Page page = new PageImpl(products, Pageable.unpaged(),count);
        return page;
    }

Limited personal level, the contents of the above description may exist where there is no clear or wrong, if the development of the students found, please let me know, I will first modify content, I hope you see buried in the New Year can only house the home case code code hard to force, give meLike a point. Your praise is my point forward momentum. Here I wish you all a happy New Year.

Published 204 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/qq330983778/article/details/104079843