Github.com/Ccww-lx/Spr…



Module: spring - the boot - base - mongo

In the era of NoSQL, App is likely to be involved in the use of MongoDB database, and it is also necessary to learn how to use Spring Data to connect MongoDB to add, delete, modify and check Data in Spring Boot. The detailed operation manual is as follows.

1. Rely on

Import the spring-data-mongodb package directly or use the Spring Boot starter

<dependencies> <! -- other dependency elements omitted --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>2.2.0.RELEASE</version> </dependency> </dependencies> <! - the spring framework using the latest - > < spring. The framework. The version > 5.2.0. RELEASE < / spring. The framework. The version > <! -- Just use it --> <! <dependency> <groupId>org.springframework. Boot </groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>Copy the code

2. Properties file application.properties

Mysql > select * from mongodb; Separated by a spring. The mongo. MongoDatabaseAddress = 10.110.112.165:27092; Dbname =mongodbopr # mongodbopr =mongodbopr # mongodbopr Spring. The mongo. Password = 123456 # mongo maximum number of connections spring. The mongo. ConnectionsPerHost = 50Copy the code

3. The mongo configuration

Register Mongo instance configuration:

@Configuration public class MongodbConfig { public static final String COMMA = ";" ; public static final String COLON = ":"; @Value("${spring.mongo.mongoDatabaseAddress}") private String mongoDatabaseAddress; @Value("${spring.mongo.username}") private String username; @Value("${spring.mongo.dbname}") private String dbname; @Value("${spring.mongo.password}") private String password; @Value("${spring.mongo.connectionsPerHost}") private String connectionsPerHost; ** @return */ private List<ServerAddress> getMongoDbAddress() {List<ServerAddress> serverAddrList =  new ArrayList<ServerAddress>(); / / if you have multiple servers if (this. MongoDatabaseAddress. IndexOf (COMMA) > 0) {String [] addressArrays = mongoDatabaseAddress.split(COMMA); String[] hostPort; for (String address : addressArrays) { hostPort = address.split(COLON); ServerAddress serverAdress = new ServerAddress(hostPort[0], Integer.valueOf(hostPort[1])); serverAddrList.add(serverAdress); } } else { String[] hostPort = mongoDatabaseAddress.split(COLON); ServerAddress serverAdress = new ServerAddress(hostPort[0], Integer.valueOf(hostPort[1])); serverAddrList.add(serverAdress); } return serverAddrList; } / set the connection parameters * * * * / private MongoClientOptions getMongoClientOptions () {MongoClientOptions. Builder Builder = MongoClientOptions.builder(); / / todo to add other parameters configuration / / maximum number of connections builder connectionsPerHost (Integer. The valueOf (connectionsPerHost)); MongoClientOptions options = builder.readPreference(ReadPreference.nearest()).build(); return options; } /** ** @return */ @bean public MongoClient MongoClient () {// MongoCredential credential = MongoCredential.createCredential(username, dbname, password.toCharArray()); Return new mongodbAddress (), credential, getMongoClientOptions()); /** * MongoTemplate public MongoTemplate * @param mongoClient * @return */ @bean@conditionalonclass (mongoclient.class) public MongoTemplate  mongoTemplate(MongoClient mongoClient) { MongoTemplate mongoTemplate = new MongoTemplate(new SimpleMongoDbFactory(mongoClient, dbname)); return mongoTemplate; }}Copy the code

4. Directing operation

Use the MongoTemplate class to add, delete, change, and query

@Service public class MongodbService { @Autowired private MongoTemplate mongoTemplate; /** @param userDTO * @return */ public userDTO insert(userDTO userDTO) { Return mongotemplate.insert (userDTO); } public UserDTO save(UserDTO userDTO) { Sort sort = new Sort(Sort.Direction.DESC, "name"); userDTO = mongoTemplate.findOne(Query.query(Criteria.where("")).with(sort), UserDTO.class); return mongoTemplate.save(userDTO); } @param */ public void remove(String name) {// Select UserDTO, UserDTO, UserDTO, UserDTO userDTO = mongoTemplate.findOne(Query.query(Criteria.where("name").is(name)), UserDTO.class); List<AddressDTO> addressList = userTo.getaddresslist (); for (AddressDTO addressDTO : addressList) { mongoTemplate.remove(addressDTO); Mongotemplate. remove(userDTO); } @param userDTO */ public void update(userDTO userDTO) { mongoTemplate.updateFirst(Query.query(Criteria.where("name").is(userDTO.getName())), Update.update("age", userDTO.getAge()), UserDTO.class); } @param name */ public void find(String name) {Sort Sort = new Sort(sort.direction.desc, "name"); List<UserDTO> userDTOS = mongoTemplate.find(Query.query(Criteria.where("name").is(name)), UserDTO.class); // Query the latest record using findOne based on sort UserDTO UserDTO = mongoTemplate.findOne(Query.query(Criteria.where("name").is(name)).with(sort), UserDTO.class); List<UserDTO> userDTOList = mongoTemplate.find(Query.query(Criteria.where("name").is(name).regex(name)).with(sort), UserDTO.class); Pageable Pageable = PageRequest. Of (3, 20, sort); List<UserDTO> userDTOPageableList = mongoTemplate.find(Query.query(Criteria.where("name").is(name)).with(pageable), UserDTO.class); Mongotemplate. count(query.query (Criteria. Where ("name").is(name)), userTo.class); // mongotemplate. count(query.query (Criteria. Page<UserDTO> page = new PageImpl(userDTOPageableList, pageable, conut); }}Copy the code

NOTE: During development, if the com.mongodb.WriteResult returned from any MongoDB operation contains errors, it is easy to log or throw exceptions. Often, it’s easy to forget to do this during development, and then end up with an App that looks like it worked, but in fact the database operation failed due to an exception. You can set the MongoTemplate WriteResultChecking property to one of the following values:

  • EXCEPTION: causeException
  • NONE: No operation is performed. Default value

For more advanced cases, where you can set a different WriteConcern value for each operation (for delete, update, insert, and save operations), you can configure the policy interface for WriteConcernResolver on MongoTemplate. Because MongoTemplate is used to persist POJOs, the WriteConcernResolver allows you to create a policy that maps specific POJO classes to WriteConcern values.

WriteConcernResolverInterface:

public interface WriteConcernResolver {
  WriteConcern resolve(MongoAction action);
}
Copy the code

The customWriteConcernResolverInterface, implementation is differentWriteConcernStrategy:

private class MyAppWriteConcernResolver implements WriteConcernResolver { public WriteConcern resolve(MongoAction action) { if (action.getEntityClass().getSimpleName().contains("UserDTO")) { return WriteConcern.NONE; } else if (action.getEntityClass().getSimpleName().contains("Metadata")) { return WriteConcern.JOURNAL_SAFE; } return action.getDefaultWriteConcern(); }}Copy the code

5. Common class and method analysis

MongoClient, ServerAddress, MongoCredential and MongoClientOptions

Use MongoClient to connect mongodb database to register mongo instance based on ServerAddress single machine or Replica Set. In the registration example, you might want to enable MongoCredential account password authentication and use MongoClientOptions to configure other mongodb parameters.

MongoClient’s common constructor methods:

public MongoClient(String host){}
public MongoClient(MongoClientURI uri){}
public MongoClient(String host, MongoClientOptions options) {}
public MongoClient(ServerAddress addr, MongoCredential credential, MongoClientOptions options){}
public MongoClient(List<ServerAddress> seeds, MongoCredential credential, MongoClientOptions options){}
Copy the code

5.2 MongoTemplate

MongoTemplate combined with Sort, Criteria, Query, Update and Pageable classes can be used to add, delete, change and check mongodb database flexibly.

The query methods:

Public <T> List<T> find(Query Query, Class<T> entityClass){} public <T> <T>findOne(Query Query, Class<T> entityClass){} public <T> List<T> findAll(Class<T> entityClass){}Copy the code

The insert method:

Public <T> T insert(T objectToSave){} public <T> T insert(T objectToSave, String collectionName) {} // public <T> T save(T objectToSave){}Copy the code

The remove method:

Public DeleteResult remove(Object Object) {} public DeleteResult remove(Query Query, Class<? > entityClass){}Copy the code

The update method:

// public UpdateResult upsert(Query query, Update update, Class<? Public UpdateResult updateFirst(Query Query, Update Update, String collectionName) {}Copy the code

5.3 the Sort

Sort Indicates the query sorting class. Sort ();

// The constructor creates a sort. Sort(sort. direction direction, String... Properties) and(Sort Sort) // return button descending()Copy the code

5.4 the Criteria

The Criteria class is similar to where in SQL.

Static method where(String key) // and(String key) // regular expression, can be fuzzy query regex(String re) // contains in(Object... O) // Greater than GT (Object O) // Greater than or equal to GTE (Object O) // Less than or equal to IS (Object O) // Less than or equal to LT (Object O) // Less than or equal to LTE (Object O) // Not () // Create and operate andOperator(Criteria... criteria)Copy the code

5.5 the Query

Query A Query object that contains all information about a Query, including filtering criteria, sorting, and returned quantity. Common methods:

// Define the query object, Static method Query (CriteriaDefinition CriteriaDefinition) // Add a CriteriaDefinition query condition addCriteria(CriteriaDefinition) to this query CriteriaDefinition) // Adds a Sort Sort object with(Sort Sort) // adds a Pageable paging object. Paging and sorting are usually used together. with(Pageable pageable)Copy the code

For more information about the MogoDB API, see the MogoDB API documentation.

6. Common notes

annotations parsing
@Id It is used to mark the ID field. Entities that do not mark this field will automatically generate the ID field, but we cannot get the ID from the entity. Id You are advised to set the ObjectId type
@Document Used to mark this entity class as the mongodb collection mapping class
@DBRef Used to specify cascading relationships with other collections, but note that cascading collections are not created automatically
@Indexed Used to mark the creation of an index for a field
@CompoundIndex Used to create a composite index
@TextIndexed: Used to mark the creation of a full-text index for a field
@Language Specify the documen language
@Transient: Those marked by this annotation will not be entered into the database. As a normal javaBean property only
@Field: Use to specify the name of a field mapped to the database


Is everyone still ok? If you like, move your hands to show 💗, point a concern!! Thanks for your support!

Welcome to pay attention to the public number [Ccww technology blog], original technical articles launched at the first time