SpringBoot integrates mongodb
MongoDB is a product between relational databases and non-relational databases. It is the most functional and similar to relational databases among non-relational databases.
If you haven't used MongoDB, you can read my article first. https://www.cnblogs.com/jiekzou/category/851166.html
Modify pom.xml to add mongodb dependencies
<!--mongodb--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
Add mongodb database connection and modify application.yml
spring:
profiles:
active: dev
# mongodb
data:
mongodb:
database: test
port: 27017
host: 192.168.1.18
Modify the original Person entity class
public class Person { @Id private Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } private String name; private String sex; public Person() { } public Person(Long id,String name, String sex) { this.id=id; this.name = name; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; }
Create a new package repository, then create a data operation layer interface PersonRepository under the package, inherit MongoRepository, code as follows:
public interface PersonRepository extends MongoRepository<Person,Long> { }
Create a controller class PersonController for add-delete check test
@RestController public class PersonController { @Autowired private PersonRepository userRepository; @GetMapping("save") public String save() { Person userInfo = new Person(System.currentTimeMillis(),"Li Xunguan","male"); userRepository.save(userInfo); return "success"; } @GetMapping("getUserList") public List<Person> getUserList() { List<Person> userInfoList = userRepository.findAll(); return userInfoList; } @GetMapping("delete") public String delete(Long id) { userRepository.delete(id); return "success"; } @GetMapping("update") public String update(Long id, String username, String password) { Person userInfo = new Person(id, username, password); userRepository.save(userInfo); return "success"; } }
Visit http://localhost:8083/boot/save, brush it several times, add a few pieces of data
Then visit http://localhost:8083/boot/getUserList to view the data
Of course, we can also use the visual mongodb management tool to see, here I use robo3t.
After configuring mysql, mongodb and other database connections, we found that basically we can not do without the following steps:
- Adding Correspondence Dependence
- Configuration file configuration corresponds to database information
- The data manipulation layer inherits the desired repository
SpringBoot refers to Thymeleaf
Thymeleaf is a template engine just like razor in. net. Spring boot is recommended to replace jsp.
Advantages of Thymeleaf
- Thymeleaf can run in both network and non-network environments, that is, it allows artists to view the static effects of pages in browsers, as well as programmers to view the dynamic effects of pages with data in servers. (When data is returned to the page, the Thymeleaf tag dynamically replaces the static content and makes the page display dynamically.)
- Thymeleaf's out-of-the-box features. (It provides two dialects, standard and spring standard, and can directly apply templates to achieve JSTL and OGNL expression effects.)
- Thymeleaf provides spring standard dialect and an optional module integrated perfectly with Spring MVC, which can quickly realize form binding, attribute editor, internationalization and other functions.
In addition, Thymeleaf is an XML/XHTML/HTML5 template engine that can be used for application development in both Web and non-Web environments. It is an open source Java library, licensed by Apache License 2.0 and created by Daniel Fern ndez, author of the Java encryption library Jasypt.
Because Thymeleaf uses an XML DOM parser, it is not suitable for processing large-scale XML files. That is to say, its performance is problematic if the file is large.
For Thymeleaf's grammar, you can refer to the official website: https://www.thymeleaf.org/documentation.html
SpringBook refers to Thymeleaf dependencies
Modify pom.xml to add the following dependencies
<!--thymeleaf--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
There is a pit here. By default, all tags in hymeleaf must appear in pairs, otherwise the IDEA runtime will report an error: "Must be terminated by a matching end tag."
Sprboot 2.0 is said to have fixed the problem with this tag, but the version I'm using here is less than 2.0, so it needs extra processing.
Continue to add dependencies
<dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency>
Then modify the configuration in application.yml.
spring:
profiles:
active: dev
thymeleaf:
mode: LEGACYHTML5
Create a new controller class to test, AreaPageController.
@Controller public class AreaPageController{ @Autowired private AreaService areaService; @GetMapping("/addArea") public String addArea(Model model) { model.addAttribute("area", new Area()); return "addArea"; } @RequestMapping(value = "/addArea",method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) public String addArea(@Valid @ModelAttribute Area area, BindingResult bindingResult){ if (bindingResult.hasErrors()) { return "addArea"; }else{ Map<String,Object> modelMap= new HashMap<String,Object>() ; modelMap.put("success",areaService.addArea(area)); return "result"; } } }
Modify the previous rea entity class, which is the same as model validation in. net mvc
package com.yujie.model; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.Date; public class Area { private Integer areaId; @NotEmpty @Size(min=2, max=30) private String areaName; @NotNull @Min(1) @Max(200) private Integer priority; private Date createTime; private Date lastEditTime;
...... }
The templates directory stores HTML files. A new HTML file addArea.html is created under the templates directory, which is equivalent to the razor view in. net mvc.
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"><!--Introduce thymeleaf--> <head> <meta charset="UTF-8" /> <title>Add area</title></head> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <body> <h2 style="color:green;text-align: center;">Add area</h2> <form class="form-horizontal" role="form" action="#" th:action="@{/addArea}" th:object="${area}" method="post"> <div class="form-group"><label for="name" class="col-sm-2 control-label">Area name:</label> <div class="col-sm-8"><input type="text" th:field="*{areaName}" class="form-control" id="areaName" placeholder="Enter area name"></div> <label class="col-sm-2" style="color:red" th:if="${#fields.hasErrors('areaName')}" th:errors="*{areaName}">Area name error</label></div> <div class="form-group"><label for="priority" class="col-sm-2 control-label">priority</label> <div class="col-sm-8"><input type="text" th:field="*{priority}" class="form-control" id="priority" placeholder="Input priority"></div> <label class="col-sm-2" style="color:red" th:if="${#fields.hasErrors('priority')}" th:errors="*{priority}">priority error</label></div> <div class="form-group"> <div class="col-sm-12" style="text-align: center"> <button type="submit" class="btn btn-primary" id="btn">Submit</button> <input type="reset" class="btn btn-warning" value="Reset"/></div> </div> </form> </body> </html>
The results are as follows:
Other learning materials: Spring Web MVC Framework (12) Using Thymeleaf