Springboot: SpringBoot in use MongoDB

MongoDB is one of the first popular non-relational databases, use is relatively common, usually offline data analysis used to use, put it in the net majority. Because many companies use cloud services, server defaults are open outside the network address, while the former leads to a large number of configuration vulnerabilities because MongoDB is attacked, the data is deleted, it attracted people's attention, but also illustrates the production of a large number of companies use many Mongodb .

Introduction to MongoDB

MongoDB (from the English word "Humongous", Chinese meaning "large") is applicable to businesses of all sizes, industries and various applications of open source database. Distributed file storage based database. Written by C ++ language. Designed to provide scalable, high-performance data storage solution for WEB applications. MongoDB is a high-performance, open source, schema-document database, the database is currently NoSql more popular one.

MongoDB is a product with function between relational databases and non-relational databases, non-relational database functions among the richest and most like a relational database. He supports the data structure is very loose, the json bjson similar format, it is possible to store more complex data types. MongoDB biggest feature is the query language supported by his very powerful, its syntax is somewhat similar to the object-oriented query language, most of the functionality can be achieved almost single-table queries similar to a relational database, but also support for data indexing.

Traditional relational databases in general by the database (database), table (table), record (record) concept consisting of three levels, MongoDB is a database (database), collection (collection), the document object (document) composed of three levels. MongoDB for relational database tables, but set no columns, rows, and the concept of relationship, which reflects the free mode features.

MongoDB is a record in a file, a data structure, from the field and value pairs. A similar document with MongoDB JSON object. Value of the field is likely to include other documents, as well as an array of array of documents. MongoDB supports OS X, Linux and Windows operating systems, and provides a Python, PHP, Ruby, Java and C ++ driver language, the community also provides a driver for the Erlang and .NET and other platforms.

MongoDB suitable for large or no fixed format data stored, such as: log, caching. Cascaded look weak support for things, do not apply more complex document (multi-table) of. This paper demonstrates Mongodb version 3.5.

MongoDB CRUD

Spring Boot all popular source of the data is encapsulated, of course, also includes Mongodb, how to introduce the following Mongodb in the Spring Boot:

1, pom package configuration

pom package which added package referencesspring-boot-starter-data-mongodb

  1. <dependencies>

  2. <dependency>

  3. <groupId>org.springframework.boot</groupId>

  4. <artifactId>spring-boot-starter-data-mongodb</artifactId>

  5. </dependency>

  6. </dependencies>

2, disposed in adding the application.properties

  1. spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test

Multiple IP cluster configuration may be adopted:

  1. spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database

2. Create a data entity

  1. public class User implements Serializable {

  2. private static final long serialVersionUID = -3258839839160856613L;

  3. private Long id;

  4. private String userName;

  5. private String passWord;

  6.  

  7. //getter、setter省略

  8. }

3, to create an entity deletions to change search operation

Layer implements Repository User objects CRUD

  1. @Component

  2. public class UserRepositoryImpl implements UserRepository {

  3.  

  4. @Autowired

  5. private MongoTemplate mongoTemplate;

  6.  

  7. /**

  8. * 创建对象

  9. * @param user

  10. */

  11. @Override

  12. public void saveUser(User user) {

  13. mongoTemplate.save(user);

  14. }

  15.  

  16. /**

  17. * 根据用户名查询对象

  18. * @param userName

  19. * @return

  20. */

  21. @Override

  22. public User findUserByUserName(String userName) {

  23. Query query=new Query(Criteria.where("userName").is(userName));

  24. User user = mongoTemplate.findOne(query , User.class);

  25. return user;

  26. }

  27.  

  28. /**

  29. * 更新对象

  30. * @param user

  31. */

  32. @Override

  33. public long updateUser(User user) {

  34. Query query=new Query(Criteria.where("id").is(user.getId()));

  35. Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());

  36. //更新查询返回结果集的第一条

  37. UpdateResult result =mongoTemplate.updateFirst(query,update,User.class);

  38. //更新查询返回结果集的所有

  39. // mongoTemplate.updateMulti(query,update,UserEntity.class);

  40. if(result!=null)

  41. return result.getMatchedCount();

  42. else

  43. return 0;

  44. }

  45.  

  46. /**

  47. * 删除对象

  48. * @param id

  49. */

  50. @Override

  51. public void deleteUserById(Long id) {

  52. Query query=new Query(Criteria.where("id").is(id));

  53. mongoTemplate.remove(query,User.class);

  54. }

  55. }

4, corresponding to the development of test methods

  1. @RunWith(SpringRunner.class)

  2. @SpringBootTest

  3. public class UserDaoTest {

  4.  

  5. @Autowired

  6. private UserDao userDao;

  7.  

  8. @Test

  9. public void testSaveUser() throws Exception {

  10. UserEntity user=new UserEntity();

  11. user.setId(2l);

  12. user.setUserName("小明");

  13. user.setPassWord("fffooo123");

  14. userDao.saveUser(user);

  15. }

  16.  

  17. @Test

  18. public void findUserByUserName(){

  19. UserEntity user= userDao.findUserByUserName("小明");

  20. System.out.println("user is "+user);

  21. }

  22.  

  23. @Test

  24. public void updateUser(){

  25. UserEntity user=new UserEntity();

  26. user.setId(2l);

  27. user.setUserName("天空");

  28. user.setPassWord("fffxxxx");

  29. userDao.updateUser(user);

  30. }

  31.  

  32. @Test

  33. public void deleteUserById(){

  34. userDao.deleteUserById(1l);

  35. }

  36.  

  37. }

5, see the validation results

You can use the tool MongoVUE tool to connect directly to a graphical display view, you can also log in to view the server with the command

1. Log mongos

bin/mongo -host localhost -port 20000

2, switch to test the library

use test

3, query user data collection

db.user.find()

3 to observe the results of the query execution of test cases is correct.

Spring Boot deletions corresponding to this change of MongoDB search function has been fully achieved.

Use of multiple data sources MongoDB

Next to realize multiple data sources using MongoDB

1, pom package configuration

  1. <dependencies>

  2. <dependency>

  3. <groupId>org.springframework.boot</groupId>

  4. <artifactId>spring-boot-starter-data-mongodb</artifactId>

  5. </dependency>

  6. <dependency>

  7. <groupId>org.springframework.boot</groupId>

  8. <artifactId>spring-boot-starter-test</artifactId>

  9. </dependency>

  10. </dependencies>

2, arranged two data sources, as follows:

  1. mongodb.primary.uri=mongodb://192.168.0.75:20000

  2. mongodb.primary.database=primary

  3. mongodb.secondary.uri=mongodb://192.168.0.75:20000

  4. mongodb.secondary.database=secondary

3, the configuration of the two data sources library

Reading the configuration file to package two beginning Mongodb

  1. @Data

  2. @ConfigurationProperties(prefix = "mongodb")

  3. public class MultipleMongoProperties {

  4.  

  5. private MongoProperties primary = new MongoProperties();

  6. private MongoProperties secondary = new MongoProperties();

  7. }

Using different data sources at different configuration package path

A first package library

  1. @Configuration

  2. @EnableMongoRepositories(basePackages = "com.neo.model.repository.primary",

  3. mongoTemplateRef = PrimaryMongoConfig.MONGO_TEMPLATE)

  4. public class PrimaryMongoConfig {

  5.  

  6. protected static final String MONGO_TEMPLATE = "primaryMongoTemplate";

  7. }

The second package library

  1. @Configuration

  2. @EnableMongoRepositories(basePackages = "com.neo.model.repository.secondary",

  3. mongoTemplateRef = SecondaryMongoConfig.MONGO_TEMPLATE)

  4. public class SecondaryMongoConfig {

  5.  

  6. protected static final String MONGO_TEMPLATE = "secondaryMongoTemplate";

  7. }

Read the corresponding configuration information and configuration corresponding MongoTemplate

  1. @Configuration

  2. public class MultipleMongoConfig {

  3.  

  4. @Autowired

  5. private MultipleMongoProperties mongoProperties;

  6.  

  7. @Primary

  8. @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)

  9. public MongoTemplate primaryMongoTemplate() throws Exception {

  10. return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));

  11. }

  12.  

  13. @Bean

  14. @Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE)

  15. public MongoTemplate secondaryMongoTemplate() throws Exception {

  16. return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));

  17. }

  18.  

  19. @Bean

  20. @Primary

  21. public MongoDbFactory primaryFactory(MongoProperties mongo) throws Exception {

  22. return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),

  23. mongo.getDatabase());

  24. }

  25.  

  26. @Bean

  27. public MongoDbFactory secondaryFactory(MongoProperties mongo) throws Exception {

  28. return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),

  29. mongo.getDatabase());

  30. }

  31. }

Two library configuration information has been completed.

4, create two libraries respectively corresponding object and Repository

You can share the corresponding

  1. public class User implements Serializable {

  2. private static final long serialVersionUID = -3258839839160856613L;

  3. private String id;

  4. private String userName;

  5. private String passWord;

  6.  

  7. public User(String userName, String passWord) {

  8. this.userName = userName;

  9. this.passWord = passWord;

  10. }

  11. }

Corresponding Repository

  1. public interface PrimaryRepository extends MongoRepository<PrimaryMongoObject, String> {

  2. }

MongoRepository will inherit the default implementation of many of the basic CRUD, save a lot of code to write their own Repository layer

Secondary and similar to the above code is not posted out

5, final test

  1. @RunWith(SpringRunner.class)

  2. @SpringBootTest

  3. public class MuliDatabaseTest {

  4.  

  5. @Autowired

  6. private PrimaryRepository primaryRepository;

  7.  

  8. @Autowired

  9. private SecondaryRepository secondaryRepository;

  10.  

  11. @Test

  12. public void TestSave() {

  13.  

  14. System.out.println("************************************************************");

  15. System.out.println("测试开始");

  16. System.out.println("************************************************************");

  17.  

  18. this.primaryRepository

  19. .save(new PrimaryMongoObject(null, "第一个库的对象"));

  20.  

  21. this.secondaryRepository

  22. .save(new SecondaryMongoObject(null, "第二个库的对象"));

  23.  

  24. List<PrimaryMongoObject> primaries = this.primaryRepository.findAll();

  25. for (PrimaryMongoObject primary : primaries) {

  26. System.out.println(primary.toString());

  27. }

  28.  

  29. List<SecondaryMongoObject> secondaries = this.secondaryRepository.findAll();

  30.  

  31. for (SecondaryMongoObject secondary : secondaries) {

  32. System.out.println(secondary.toString());

  33. }

  34.  

  35. System.out.println("************************************************************");

  36. System.out.println("测试完成");

  37. System.out.println("************************************************************");

  38. }

  39.  

  40. }

 

Guess you like

Origin www.cnblogs.com/meizhoulqp/p/11281089.html