1, MongoDB configuration
1. Import jar package
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
2. Configuration of mongodb basic scanning package
1.In the configuration file bootstrap.properties Add driver to spring.data.mongodb.uri = mongodb://root:root@localhost:27017/test 2.Configure the base scan package in the configuration file xml In the file or in the java.config Class to configure the basic scan class
3. Declare entity and repository
@Data //Automatically generate annotations in the lombok package of get, set and toString methods @Document(collection = "t_user") //collection corresponds to the indication in the database public class User { //entity class private String id; private String userName; private int age; private int isDelete = 1; //The field 0 used for false deletion represents normal deletion of 1 } public interface UserRepository extends MongoRepository<User,String> { User findOneByName(String userName); //Unique user name }
2, Native method of MongoRepository (can be called directly)
1. Total count
//Source code of implementation method public long count() { return this.mongoOperations.getCollection(this.entityInformation.getCollectionName()).count(); } //The return value is of long type. Function: count the number of data in the table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public long getCOuntofUser(){ return userRepository.count(); } }
2. count (example < T > example) condition statistics total
Before using this method, I will first explain the class example, which is often used in the future. It consists of the following two parts: 1.Probe: a specific example of a domain object. 2.ExampleMatcher carries the details of how to match specific fields. It can be reused between multiple Examples.
"Scope of application": ① when using a set of static or dynamic constraints to query; ② Frequently reconstruct domain objects without worrying about destroying existing queries; ③ Independent of the underlying data storage API
Defect: ① nested / grouped property constraints are not supported, such as firstname =? 0 or (firstname = ?1 and lastname = ?2); ② Only starts/contains/ends/regex matches of strings and other types of exact matches are supported.
"Usage rules":
// Create an instance of domain object. User user = new User(); // Set the properties to query. You can set multiple parameters user.setUserName("Bob"); user.setAge(18); //Create Example Example<User> example = Example.of(user);
3. count(Exampleexample):
//Source code of implementation method public <S extends T> long count(Example<S> example) { Assert.notNull(example, "Sample must not be null!"); Query q = new Query((new Criteria()).alike(example)); return this.mongoOperations.count(q, example.getProbeType(), this.entityInformation.getCollectionName()); } //The return value is of long type. Function: count the number of data in the conditional statistics table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public long getCOuntofUser(User user){ Example<User> example = Example.of(user); return userRepository.count(); } }
4. delete (T) deletes a piece of data through the object information
//The source code of the implementation method is deleted through id at the bottom public void delete(T entity) { Assert.notNull(entity, "The given entity must not be null!"); this.delete(this.entityInformation.getId(entity)); } //The return value is of void type. The function is to delete a piece of data in the table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public void deleteOneUser(User user){ userRepository.delete(user); } }
5. delete (id) deletes a piece of data by id
//The source code of the implementation method is deleted through id at the bottom public void delete(ID id) { Assert.notNull(id, "The given id must not be null!"); this.mongoOperations.remove(this.getIdQuery(id), this.entityInformation.getJavaType(), this.entityInformation.getCollectionName()); } //The return value is of void type. The function is to delete a piece of data in the table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public void deleteOneUser(String id){ userRepository.delete(user); } }
6. delete (Iterable <? Extends Apple > Iterable) deletes a piece of data in batch
//The source code of the implementation method is deleted in batch. The bottom layer is deleted through id public void delete(Iterable<? extends T> entities) { Assert.notNull(entities, "The given Iterable of entities not be null!"); Iterator var2 = entities.iterator(); while(var2.hasNext()) { T entity = var2.next(); this.delete(entity); } } //The return value is of void type. Function: batch deletion @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public void deleteUsers(List<User> users){ userRepository.delete(users); } }
7. deleteAll() clears all data in the table
//Source code of implementation method public void deleteAll() { this.mongoOperations.remove(new Query(), this.entityInformation.getCollectionName()); } //The return value is of void type. Function: all data in the empty table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public void deleteAll(){ userRepository.deleteAll(); } }
8. exists (ID) determines whether the data exists
//Source code of implementation method public boolean exists(ID id) { Assert.notNull(id, "The given id must not be null!"); return this.mongoOperations.exists(this.getIdQuery(id), this.entityInformation.getJavaType(), this.entityInformation.getCollectionName()); } //The return value is of boolean type. Function: judge whether the data exists @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public boolean isExist(String id){ return userRepository.exists(id); } }
9. exists (example < T > example) determines whether a specific data exists
//Source code of implementation method public <S extends T> boolean exists(Example<S> example) { Assert.notNull(example, "Sample must not be null!"); Query q = new Query((new Criteria()).alike(example)); return this.mongoOperations.exists(q, example.getProbeType(), this.entityInformation.getCollectionName()); } //The return value is of boolean type. Function: judge whether a specific data exists @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public boolean isExist(User user){ Example example = Example.of(user); return userRepository.exists(example); } }
10. findAll() gets all the data in the table
//Source code of implementation method public List<T> findAll() { return this.findAll(new Query()); } //The return value is of type list < user > and its function is to obtain all data in the table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public List<User> findAll(){ return userRepository.findAll(); } }
11. findAll (Sort sort) gets all the data in the table and sorts it according to a specific field
//Source code of implementation method public List<T> findAll(Sort sort) { return this.findAll((new Query()).with(sort)); } //The return value is of type list < user > and its function is to obtain and sort all the data in the table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public List<User> findAll(){ Sort sort = new Sort(Sort.Direction.ASC,"id"); //The second parameter is a variable length parameter, which can pass multiple values return userRepository.findAll(sort); }
12. findAll (Pageable pageAble) obtains all the data in the table and performs paging query
//Source code of implementation method public Page<T> findAll(Pageable pageable) { Long count = this.count(); List<T> list = this.findAll((new Query()).with(pageable)); return new PageImpl(list, pageable, count); } //The return value is of page < user > type. Function: page query to obtain data in the table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public Page<User> findAll(int page, int size){ Pageable pageable = new PageRequest(page,size); return userRepository.findAll(pageable); } } //It is worth noting that PageRequest has several constructors, namely: /* *1.page Refers to the current page, and size represents the number of entries per page; *Function: paging query */ public PageRequest(int page, int size) { this(page, size, (Sort)null); } /* *2.page Refers to the current page, size represents the number of entries per page, and sort represents the number of sorted entries *Method (the implementation method of sort is described above, so I won't repeat it *Function: paging query and sorting */ public PageRequest(int page, int size, Sort sort) { super(page, size); this.sort = sort; } /* *3.page Refers to the current page, size represents the number of entries per page, and sort represents the number of sorted entries *Method, properties variable length parameter, representing query criteria *Function: query and sort by paging conditions */ public PageRequest(int page, int size, Direction direction, String... properties) { this(page, size, new Sort(direction, properties)); }
13. findAll (example < T > example) condition query
//Source code of implementation method public <S extends T> List<S> findAll(Example<S> example) { return this.findAll(example, (Sort)null); } //The return value is of type list < user > and its function is to obtain all data in the table by conditions @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public List<User> findAll(user){ Example example = Example.of(user); return userRepository.findAll(example); } }
14. findAll (iteratable IDS) condition query
//Source code of implementation method public Iterable<T> findAll(Iterable<ID> ids) { Set<ID> parameters = new HashSet<ID>(tryDetermineRealSizeOrReturn(ids, 10)); for (ID id : ids) { parameters.add(id); } return findAll(new Query(new Criteria(entityInformation.getIdAttribute()).in(parameters))); } //The return value is of type List < user > and its function is to obtain all data in all lists @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public List<User> findAll(List<String> ids){ //Here, the parameters are limited to the set of IDS return userRepository.findAll(ids); } }
15. findAll (example < T > example, pageable pageable) conditional paging query
//Source code of implementation method public <S extends T> Page<S> findAll(final Example<S> example, Pageable pageable) { Assert.notNull(example, "Sample must not be null!"); final Query q = new Query(new Criteria().alike(example)).with(pageable); List<S> list = mongoOperations.find(q, example.getProbeType(), entityInformation.getCollectionName()); return PageableExecutionUtils.getPage(list, pageable, new TotalSupplier() { @Override public long get() { return mongoOperations.count(q, example.getProbeType(), entityInformation.getCollectionName()); } }); } //The return value is of page < user > type. Function: obtain all data in the table and page @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public Page<User> findAll(int page,int size,User user){ Example example = Example.of(user); Pageable pageable = new PageRequest(page,size); return userRepository.findAll(example ,pageable ); } }
16. findAll (example < T > example, sort sort) conditional query sorting
//Source code of implementation method public <S extends T> List<S> findAll(Example<S> example, Sort sort) { Assert.notNull(example, "Sample must not be null!"); Query q = new Query(new Criteria().alike(example)); if (sort != null) { q.with(sort); } return mongoOperations.find(q, example.getProbeType(), entityInformation.getCollectionName()); } //The return value is of type list < user > and its function is to obtain all data in the table by conditions @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public List<User> findAll(User user){ Example<User> example = Example.of(user); Sort sort = new Sort(Sort.Direction.ASC,"userName"); return userRepository.findAll(ids); } }
17. findOne (String id) queries a piece of data by id
//Source code of implementation method public T findOne(ID id) { Assert.notNull(id, "The given id must not be null!"); return mongoOperations.findById(id, entityInformation.getJavaType(), entityInformation.getCollectionName()); } //The return value is User type. Function: get a piece of data in the table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public User findOne(String id){ return userRepository.findOne(id); } }
18. findOne (example) queries a piece of data by id
//Source code of implementation method public <S extends T> S findOne(Example<S> example) { Assert.notNull(example, "Sample must not be null!"); Query q = new Query(new Criteria().alike(example)); return mongoOperations.findOne(q, example.getProbeType(), entityInformation.getCollectionName()); } //The return value is User type. Function: get a piece of data in the table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public User findOne(String userName){ User user = new User(); user.setUserName(userName); Example<User> example = Example.of(user); return userRepository.findOne(example); } }
19. Insert (T) inserts a piece of data
//Source code of implementation method public <S extends T> S insert(S entity) { Assert.notNull(entity, "Entity must not be null!"); mongoOperations.insert(entity, entityInformation.getCollectionName()); return entity; } //The return value is of User type. Function: add a piece of data to the table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public User insert(User user){ return userRepository.insert(user); } }
20. Insert (Iterable < T > Iterable) inserts multiple pieces of data
//Source code of implementation method public <S extends T> List<S> insert(Iterable<S> entities) { Assert.notNull(entities, "The given Iterable of entities not be null!"); List<S> list = convertIterableToList(entities); if (list.isEmpty()) { return list; } mongoOperations.insertAll(list); return list; } //The return value is User type. Function: add multiple pieces of data to the table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public User insert(List<User> users){ return userRepository.insert(users); } }
21. Save (T) saves a piece of data
//Source code of implementation method public <S extends T> S save(S entity) { Assert.notNull(entity, "Entity must not be null!"); if (entityInformation.isNew(entity)) { mongoOperations.insert(entity, entityInformation.getCollectionName()); } else { mongoOperations.save(entity, entityInformation.getCollectionName()); } return entity; } //The return value is of User type. Function: add a piece of data to the table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public User insert(User user){ return userRepository.save(user); } }
22. Save (Iterable < T > Iterable) adds multiple pieces of data
//Source code of implementation method public <S extends T> List<S> save(Iterable<S> entities) { Assert.notNull(entities, "The given Iterable of entities not be null!"); List<S> result = convertIterableToList(entities); boolean allNew = true; for (S entity : entities) { if (allNew && !entityInformation.isNew(entity)) { allNew = false; } } if (allNew) { mongoOperations.insertAll(result); } else { for (S entity : result) { save(entity); } } return result; } //The return value is of type list < user > and its function is to add multiple pieces of data to the table @Service public class UserServiceImpl { @Autowired private UserRepository userRepository; public User insert(List<User> users){ return userRepository.save(users); } }
3, Summary:
"Both save() and insert() in the native method add a piece of data to the table. What's the difference between them?"
Official document description:
1.Updates an existing document or inserts a new document, depending on its document parameter
2.If the document does not contain an _id field, then the save() method calls the insert() method. During the operation, the mongo shell will create an ObjectId and assign it to the _id field.
Meaning: the save () method updates an existing file or inserts a piece of data, depending on a field in a file. If a file does not contain an id, then the save () method directly calls the insert () method and generates an id; if an id is included, it is updated directly.
//Without _id parameter db.products.save( { userName: "Lushirui", age: 20 } ) //result { "_id" : ObjectId("50691737d386d8fadbd6b01d"), "userName " : "userName ", "age" : 20} //With _id parameter, but an existing document cannot be found db.products.save( { _id: 100, userName: "Lujianlong", age: 20 } ) //result { "_id" : 100, userName : "Lujianlong", "age" : 20 }
1.insert: if the primary key of the new data already exists, an org.springframework.dao.Duplicate KeyException will be thrown, prompting that the primary key is duplicate and the current data will not be saved.
2.save: if the primary key of the new data already exists, the existing data will be modified.