1. Preface
In our enterprise development, the most commonly used are relational databases (oracle, mysql, sqlserver, etc.). These jdbc-Based data interaction methods can be achieved by integrating mybatis in spring, which is explained in this series of articles "Spring Series - Actual Warfare (4) - How you know MyBatis".
However, for non-relational databases, i.e. nosql databases, mybatis cannot be used directly because they do not even have sql, and jdbc is essentially a java api for executing SQL statements.This article takes mongodb, a member of nosql database, as an example.Explain the features of mongodb database and how to implement common add-delete checks in springboot.
2.mongo
2.1. Introduction
mongodb is a document-oriented, non-relational database. The main reason to abandon the relational model is to get more convenient scalability, but not only that.
Rich data model: Document keys (corresponding to relational databases: table fields) are not predefined or fixed, and are flexible to develop.Field values are rich in types and can contain other documents, arrays, and document arrays, so a single record can represent very complex hierarchical relationships.
Easy to extend: mongodb was originally designed with extensions in mind.It uses a document-oriented data model that allows it to automatically split data across multiple servers.It also balances the data and load of the cluster and automatically rearranges the documents.
Rich features: There are many powerful assistive tools to make mongodb more powerful.(1) You can stop writing stored procedures in the database, allow scripts to be executed on the server side, write a function in Javascript, execute directly on the server side, or store the definition of the function on the server side, and call it directly next time.(2) Big data applications are also supported by mapreduce and other aggregation tools.
For those friends who first came into contact with mongodb, let me first list a comparison table of the basic concepts of mysql and mongodb databases.
| mysql concept | mongo concept |
| ---- | ---- |
| table | collection |
| row (record line) | document |
|column (data field)|field (field)|
| index | index | index |
|primary key|Automatically set the _id field as the primary key|
|table joins|Not supported|
2.2. Installation and use
As mentioned in the previous section, mongodb is designed for distributed scaling and there are many configurations to consider when building mongo clusters.However, this is not the content to be introduced in this article. This article mainly focuses on the application of springboot+mongodb.We are easy to container environments, and the easiest way to start a mongodb database is to do so.
docker run --name domain-mongodb -v /u01/mongo/data/db:/data/db -p 27017:27017 -d mongo
Follow the command above, and a mongodb is started, mapped to the outside port is 27017.
Just like we're using oracle databases, we're using sql/plsql developer clients; mysql databases, navicat clients; mongodb, I recommend robo 3T .robo 3T is free, and there is also studio 3T software on the download page, which is commercially charged and of course has more features.
Once the installation is complete and started, connect to mongodb on the server.Just like we create a database and then tables in a mysql database.Let's create the collection first, then the document. Note that mongodb doesn't need a preset table structure, so just fill in the name of the document.In the following figure, three documents under the portal collection are created, oauth_client, oauth_config, and user.
3.springboot code
Next, we will take springboot as an example to illustrate how to implement the simplest add-delete check on mongodb data.
3.1. Configuration
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>2.0.3.RELEASE</version> </dependency>
application.yml
spring: data: mongodb: uri: mongodb://ip:port/collection name
3.2.pojo
First create a pojo class, UserEO.java, which corresponds to the user document created in the previous mongodb. Here are a few points of knowledge.
- @Document: This annotation binds the relationship between the pojo class and the mongodb document.
- @Field: This annotation binds the relationship between the field name in the pojo class and the field in the mongodb document.
- The value of the List <UserBookEO> bookList:mongodb field can be not only the base field, but also other documents, arrays, document arrays, and so on.
@Document(collection = "user") public class UserEO { private String username; private String password; private String name; /** * Creation Time */ @JsonFormat(pattern="yyyy.MM.dd HH:mm:ss",timezone = "GMT+8") @Field("creation_date") private Date creationDate; /** * UserBookEO Class: name, price, amount */ private List<UserBookEO> bookList; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public List<UserBookEO> getBookList() { return bookList; } public void setBookList(List<UserBookEO> bookList) { this.bookList = bookList; } }
3.3. dao
The operation of the dao layer mainly depends on the implementation of MongoTemplate. The most commonly used additions, deletions, and paging queries are listed in the following code. For more advanced usage, you can go to the official website to see the source implementation of MongoTemplate.
@Component public class PaasDao { @Autowired private MongoTemplate mongoTemplate; /** * Paging query user * * @param key * @return */ public List<UserEO> queryUsers(String key, int page, int pageSize) { Query query = new Query(); Criteria criteriaUsername = Criteria.where("username").regex(key); Criteria criteriaName = Criteria.where("name").regex(key); query.addCriteria(new Criteria().orOperator(criteriaUsername, criteriaName)); //paging Sort sort=new Sort(Sort.Direction.DESC, "creation_date"); Pageable pageable=PageRequest.of(page-1,pageSize,sort); query.with(pageable); return mongoTemplate.find(query, UserEO.class); } /** * Delete client * * @param username */ public void deleteUser(String username) { Query query = new Query(Criteria.where("username").is(username)); mongoTemplate.remove(query, UserEO.class); } /** * New client * * @param user */ public void addUser(UserEO user) { user.setCreationDate(new Date()); mongoTemplate.save(user); } /** * Update user * * @param user */ public void updateUser(UserEO user) { Query query = new Query(Criteria.where("username").is(user.getUsername())); Update update = new Update().set("password", user.getPassword()) .set("name",user.getName()); mongoTemplate.updateFirst(query, update, UserEO.class); } /** * Query the number of username s that exist * * @param username * @return */ public long countUsername(String username) { Query query = new Query(Criteria.where("username").is(username)); return mongoTemplate.count(query, UserEO.class); } }
3.4. Interface testing
There aren't much to show in the controller layer, so I'll simply test the two new interfaces with query.
@RestController @RequestMapping(value = "/paas") public class PaasController { @Autowired private PaasDao paasDao; /** * user - Query Users * * @param request * @return */ @RequestMapping(value = "/user/queryUsers", method = RequestMethod.POST) public Response queryUsers(@RequestBody Map<String, Object> request) { Integer page = (Integer) request.get("page"); Integer pageSize = (Integer) request.get("pageSize"); String key = request.get("key") == null ? "" : (String) request.get("key"); List<UserEO> userEOList=paasDao.queryUsers(key,page,pageSize); long userCount=paasDao.countUsers(key); PageQueryResult<UserEO> pageQueryResult = new PageQueryResult<>(userCount,userEOList); return Response.ok().data(pageQueryResult); } /** * user - New Users * * @param userEO * @return */ @RequestMapping(value = "/user/addUser", method = RequestMethod.POST) public Response addUser(@RequestBody UserEO userEO) { paasDao.addUser(userEO); return Response.ok(); }
With the new interface, we passed in two sets of data:
//First set of data { "username":"kerry", "password":"kerry", "name":"Wu Chenrui" } //Second set of data { "username":"tony", "password":"tony", "name":"Tony", "bookList":[ { "name":"The Dream of Red Mansion", "price":20, "amount":1 }, { "name":"The Three Musketeers: One for All!", "price":10, "amount":2 } ] }
After successful insertion, we query the database through robo 3T to verify that the data was inserted successfully.
Next, call the query interface and return the following results:
{ "code":"ok", "data":{ "count":2, "result":[ { "username":"tony", "password":"tony", "name":"Tony", "creationDate":"2019.11.17 16:29:34", "bookList":[ { "name":"The Dream of Red Mansion", "price":20, "amount":1 }, { "name":"The Three Musketeers: One for All!", "price":10, "amount":2 } ] }, { "username":"kerry", "password":"kerry", "name":"Wu Chenrui", "creationDate":"2019.10.30 10:53:55" } ] }, "requestid":"e80b71d50c9e45e9bffa3bd0b2abf446" }
OK, it doesn't seem difficult to develop mongodb-based interfaces within the springboot framework.