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
-
<dependencies>
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-data-mongodb</artifactId>
-
</dependency>
-
</dependencies>
2, disposed in adding the application.properties
-
spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test
Multiple IP cluster configuration may be adopted:
-
spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database
2. Create a data entity
-
public class User implements Serializable {
-
private static final long serialVersionUID = -3258839839160856613L;
-
private Long id;
-
private String userName;
-
private String passWord;
-
-
//getter、setter省略
-
}
3, to create an entity deletions to change search operation
Layer implements Repository User objects CRUD
-
@Component
-
public class UserRepositoryImpl implements UserRepository {
-
-
@Autowired
-
private MongoTemplate mongoTemplate;
-
-
/**
-
* 创建对象
-
* @param user
-
*/
-
@Override
-
public void saveUser(User user) {
-
mongoTemplate.save(user);
-
}
-
-
/**
-
* 根据用户名查询对象
-
* @param userName
-
* @return
-
*/
-
@Override
-
public User findUserByUserName(String userName) {
-
Query query=new Query(Criteria.where("userName").is(userName));
-
User user = mongoTemplate.findOne(query , User.class);
-
return user;
-
}
-
-
/**
-
* 更新对象
-
* @param user
-
*/
-
@Override
-
public long updateUser(User user) {
-
Query query=new Query(Criteria.where("id").is(user.getId()));
-
Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());
-
//更新查询返回结果集的第一条
-
UpdateResult result =mongoTemplate.updateFirst(query,update,User.class);
-
//更新查询返回结果集的所有
-
// mongoTemplate.updateMulti(query,update,UserEntity.class);
-
if(result!=null)
-
return result.getMatchedCount();
-
else
-
return 0;
-
}
-
-
/**
-
* 删除对象
-
* @param id
-
*/
-
@Override
-
public void deleteUserById(Long id) {
-
Query query=new Query(Criteria.where("id").is(id));
-
mongoTemplate.remove(query,User.class);
-
}
-
}
4, corresponding to the development of test methods
-
@RunWith(SpringRunner.class)
-
@SpringBootTest
-
public class UserDaoTest {
-
-
@Autowired
-
private UserDao userDao;
-
-
@Test
-
public void testSaveUser() throws Exception {
-
UserEntity user=new UserEntity();
-
user.setId(2l);
-
user.setUserName("小明");
-
user.setPassWord("fffooo123");
-
userDao.saveUser(user);
-
}
-
-
@Test
-
public void findUserByUserName(){
-
UserEntity user= userDao.findUserByUserName("小明");
-
System.out.println("user is "+user);
-
}
-
-
@Test
-
public void updateUser(){
-
UserEntity user=new UserEntity();
-
user.setId(2l);
-
user.setUserName("天空");
-
user.setPassWord("fffxxxx");
-
userDao.updateUser(user);
-
}
-
-
@Test
-
public void deleteUserById(){
-
userDao.deleteUserById(1l);
-
}
-
-
}
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
-
<dependencies>
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-data-mongodb</artifactId>
-
</dependency>
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-test</artifactId>
-
</dependency>
-
</dependencies>
2, arranged two data sources, as follows:
-
mongodb.primary.uri=mongodb://192.168.0.75:20000
-
mongodb.primary.database=primary
-
mongodb.secondary.uri=mongodb://192.168.0.75:20000
-
mongodb.secondary.database=secondary
3, the configuration of the two data sources library
Reading the configuration file to package two beginning Mongodb
-
@Data
-
@ConfigurationProperties(prefix = "mongodb")
-
public class MultipleMongoProperties {
-
-
private MongoProperties primary = new MongoProperties();
-
private MongoProperties secondary = new MongoProperties();
-
}
Using different data sources at different configuration package path
A first package library
-
@Configuration
-
@EnableMongoRepositories(basePackages = "com.neo.model.repository.primary",
-
mongoTemplateRef = PrimaryMongoConfig.MONGO_TEMPLATE)
-
public class PrimaryMongoConfig {
-
-
protected static final String MONGO_TEMPLATE = "primaryMongoTemplate";
-
}
The second package library
-
@Configuration
-
@EnableMongoRepositories(basePackages = "com.neo.model.repository.secondary",
-
mongoTemplateRef = SecondaryMongoConfig.MONGO_TEMPLATE)
-
public class SecondaryMongoConfig {
-
-
protected static final String MONGO_TEMPLATE = "secondaryMongoTemplate";
-
}
Read the corresponding configuration information and configuration corresponding MongoTemplate
-
@Configuration
-
public class MultipleMongoConfig {
-
-
@Autowired
-
private MultipleMongoProperties mongoProperties;
-
-
@Primary
-
@Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)
-
public MongoTemplate primaryMongoTemplate() throws Exception {
-
return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
-
}
-
-
@Bean
-
@Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE)
-
public MongoTemplate secondaryMongoTemplate() throws Exception {
-
return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
-
}
-
-
@Bean
-
@Primary
-
public MongoDbFactory primaryFactory(MongoProperties mongo) throws Exception {
-
return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
-
mongo.getDatabase());
-
}
-
-
@Bean
-
public MongoDbFactory secondaryFactory(MongoProperties mongo) throws Exception {
-
return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
-
mongo.getDatabase());
-
}
-
}
Two library configuration information has been completed.
4, create two libraries respectively corresponding object and Repository
You can share the corresponding
-
public class User implements Serializable {
-
private static final long serialVersionUID = -3258839839160856613L;
-
private String id;
-
private String userName;
-
private String passWord;
-
-
public User(String userName, String passWord) {
-
this.userName = userName;
-
this.passWord = passWord;
-
}
-
}
Corresponding Repository
-
public interface PrimaryRepository extends MongoRepository<PrimaryMongoObject, String> {
-
}
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
-
@RunWith(SpringRunner.class)
-
@SpringBootTest
-
public class MuliDatabaseTest {
-
-
@Autowired
-
private PrimaryRepository primaryRepository;
-
-
@Autowired
-
private SecondaryRepository secondaryRepository;
-
-
@Test
-
public void TestSave() {
-
-
System.out.println("************************************************************");
-
System.out.println("测试开始");
-
System.out.println("************************************************************");
-
-
this.primaryRepository
-
.save(new PrimaryMongoObject(null, "第一个库的对象"));
-
-
this.secondaryRepository
-
.save(new SecondaryMongoObject(null, "第二个库的对象"));
-
-
List<PrimaryMongoObject> primaries = this.primaryRepository.findAll();
-
for (PrimaryMongoObject primary : primaries) {
-
System.out.println(primary.toString());
-
}
-
-
List<SecondaryMongoObject> secondaries = this.secondaryRepository.findAll();
-
-
for (SecondaryMongoObject secondary : secondaries) {
-
System.out.println(secondary.toString());
-
}
-
-
System.out.println("************************************************************");
-
System.out.println("测试完成");
-
System.out.println("************************************************************");
-
}
-
-
}