CGB2107-Day06-SpringBoot integrates Mybatis
1. Supplementary knowledge of mybatis
1.1 special description of parameter value
<!-- Knowledge points: 1. Formal parameter/Arguments pass values,It has nothing to do with the name. 2. resultMap When the hump mapping rule is turned on,Can be mapped automatically,Then use resultType that will do. 3. If mybatis There is only one parameter passed,be mybatis Is to use subscript value. So the name is arbitrary #{xxxx}, but generally we need to pay attention to the development specifications --> <select id="findDeptById" resultType="Dept"> select * from dept where dept_id = #{id} </select>
1.2 proxy object description
1.2.1 common dynamic agents
- JDK dynamic agent
characteristic:
1. It is required that the agent must implement (have) interfaces
2.JDK agent is provided by jdk by default - CGLIB dynamic proxy
characteristic:
1. No matter whether the agent has an interface or not, you can create a proxy object for it The proxy object is a subclass of the target object
2.cglib needs to import the jar package manually
3.spring automatically adds cglib dependencies for the convenience of creating proxy objects
1.2.2 Mapper interface description
/** * Case description: query department information according to id * Description of object creation: * 1.DeptMapper Is an interface Interface cannot instantiate object directly!!! * 2.The DeptMapper obtained is a proxy object dynamically generated by JDK for the interface * 3.The function of calling proxy object is consistent with that of interface */ @Test public void testFindDeptById(){ SqlSession sqlSession = sqlSessionFactory.openSession(); DeptMapper deptMapper = sqlSession.getMapper(DeptMapper.class); System.out.println(deptMapper.getClass()); int id = 100; Dept dept = deptMapper.findDeptById(id); System.out.println(dept); sqlSession.close(); }
2. Integration of three frameworks
2.1 framework overview
2.1.1 Spring framework
Spring integrates complex frameworks for team development, making the program integrate from control to call Call in a unified way
Core: integrate the third-party framework
2.1.2 core mechanism of spring framework
- IOC:
Inversion of control: the right to create objects is handed over to the Spring container, which manages the life cycle of objects
DI: dependency injection
When creating an object, Spring is responsible for assigning a value to the attribute if the object has a dependent attribute
@RestController public class UserController { @Autowired private UserService userService; } 12345
- AOP aspect oriented programming
2.1.2 SpringMVC
Note: the main function of this framework is to receive the user's request, complete the business processing, and finally return the response to the user
2.1.3 calling relationship between frameworks
2.2 realization of project integration
2.2.1 create project
- Create project
Select the springBoot version
2.2.2 edit POM XML file
Note: copy the POM in the previous project The XML file format is as follows
<!--You only need to copy files other than coordinates--> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring-boot.version>2.4.1</spring-boot.version> </properties> <dependencies> <!--springBoot integration mvc--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--springBoot Integration test method--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--Support hot deployment and effective development phase--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <!--Introducing plug-ins lombok automatic set/get/Constructor plug-in --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--mybatis Package dependency--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!--jdbc Package dependency--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.4.1</version> <configuration> <mainClass>com.jt.SpringbootDemo1Application</mainClass> </configuration> <!--Exclude some specified configurations--> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
2.3 editing core code
2.3.1 edit User's POJO
package com.jt.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; @Data @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor public class User implements Serializable { private Integer id; private String name; private Integer age; private String sex; }
2.3.2 editing Mapper interface
package com.jt.mapper; import com.jt.pojo.User; import java.util.List; public interface UserMapper { //Query demo_ All data in the user table List<User> findAll(); }
2.3.3 editing xml Mapping Files
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.jt.mapper.UserMapper"> <select id="findAll" resultType="com.jt.pojo.User"> select * from demo_user </select> </mapper>
2.3.4 edit Service interface and implementation class
1. Edit UserService interface
package com.jt.service; import com.jt.pojo.User; import java.util.List; public interface UserService { //Query all data in user table List<User> findAll(); }
2. Edit ServiceImpl implementation class
package com.jt.service; import com.jt.mapper.UserMapper; import com.jt.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.util.List; @Service //Leave this class to the Spring container to manage public class UserServiceImpl implements UserService{ @Autowired private UserMapper userMapper; //Proxy object JDK dynamic proxy @Override public List<User> findAll() { //List<User> userList = userMapper.findAll(); //return userList; return userMapper.findAll(); } }
2.3.5 editing Controller
package com.jt.controller; import com.jt.pojo.User; import com.jt.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController //@When the Controller gives this class to the Spring container to manage the return value of + / / @ ResponseBody business, it converts the data into JSON public class UserController { @Autowired private UserService userService; /** * Requirement: query all user table data * Request type: get/post/put/delete * Path: / findUser * Parameter: None * Return value: List < user > */ @RequestMapping("/getUser") public List<User> findUser(){ return userService.findAll(); } }
2.4 edit core configuration - application yml
2.4.1 data source configuration
Link writing:
- serverTimezone=GMT%2B8 specified time zone east zone 8
- useUnicode=true&characterEncoding=utf8
Enable Unicode encoding and specify the character set utf-8 - autoReconnect=true whether to relink after disconnection
- &Allowmultiqueries = true allow batch operations
2.4.2 editing yml files
#Syntax: 1 Key: (space) value structure server: port: 8090 #Consolidate data sources spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/jt?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true username: root password: root #Spring boot integrates mybatis mybatis: #Specify alias package type-aliases-package: com.jt.pojo #Loads the specified xml Mapping file mapper-locations: classpath:/mybatis/mappers/*.xml #Turn on hump mapping configuration: map-underscore-to-camel-case: true
2.5 Spring management Mapper interface
2.5.1 description of error reporting
2.5.2 @Mapper and @ MapperScan annotations
- @Mapper
- @MapperScan simplifies configuration information through package scanning
2.6 description of integrated error reporting
2.6.1 binding exception
- Check the namespace in the xml Mapping file
- Check the ID of Sql in the xml Mapping file
3. Check the import of xml Mapping file in YML file
Check whether the YML file is freeze frame and whether there is hierarchical indentation
4. Check @ MapperScan("com.jt.mapper")
2.6.2 abnormal database link
Description of error report: abnormal database link
Check database link address / username / password
3. Restful realizes parameter transfer
3.1 query data according to ID
3.1.1 request path
Get request type:
url:http://localhost:8090/findUserById?id=1
3.1.2 editing UserController
/** * Business: query user data according to ID * Request type: get * URL:http://localhost:8090/findUserById?id=1 * Parameter: id=1 * Return value: User object * SpringMVC Business specification: * 1.When receiving parameters, they must be consistent with user parameters */ //@RequestMapping(value = "findUserById",method = RequestMethod.GET) @GetMapping("findUserById") //Only Get request types can be received public User findUserById(Integer id){ return userService.findUserById(id); }
3.1.3 edit UserService interface / implementation class
1. Edit business interface
-
Editing concrete implementation
package com.jt.service; import com.jt.mapper.UserMapper; import com.jt.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.util.List; @Service //Leave this class to the Spring container to manage public class UserServiceImpl implements UserService{ @Autowired private UserMapper userMapper; //Proxy object JDK dynamic proxy @Override public User findUserById(Integer id) { return userMapper.findUserById(id); } }
3.1.4 edit Mapper interface / mapping file
1. Edit Mapper interface
- Edit xml Mapping File
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.jt.mapper.UserMapper"> <select id="findUserById" resultType="User"> select * from demo_user where id = #{id} </select> </mapper>
4 framework integration
- It is required to query user information according to name and age
URL: http://localhost:8090/findUserByNA?name=xxx&age=xxx - The name of the query ends with "xxx"
URL: http://localhost:8090/findUserLike?name=xx - Query data with id 1,3,5,6,7
URL: http://localhost:8090/findUserByIds?id=1,3,5,6,7 - Query data according to non null elements in the object dynamic Sql query
URL: http://localhost:8090/findUser?id=xx&name="xx"&age=xx&sex=xx
URL: http://localhost:8090/findUser?age=xx&sex=xx
URL: http://localhost:8090/findUser?sex=xx - The update operation uses the structure of restFul to modify the data according to the Id and modify the name/age
URL:http://localhost:8090/user/ Diao Chan / 18 / 227
Resolution: URL:http://localhost:8090/user/{name}/{age}/{id}
5 spring MVC parameter passing
5.1 description of front-end controller
Front end controller: mainly responsible for receiving user requests and distributing back-end business processing
5.2 Servlet
5.2.1 what is a Servlet
Servlet (Server Applet) is the abbreviation of Java Servlet, which is called small service program or service connector. The server-side program written in Java is independent of platform and protocol. Its main function is to interactively browse and generate data and generate dynamic Web content.
Servlet in the narrow sense refers to an interface implemented by java language. Servlet in the broad sense refers to any class that implements the servlet interface. Generally, people understand servlet as the latter. The servlet runs in an application server that supports Java. In principle, servlets can respond to any type of request, but in most cases, servlets are only used to extend Web servers based on HTTP protocol.
Summary: Servlet is the mechanism (medium) for java background program to interact with users
5.2.2 cases of collusion
//http://localhost:8090/findUserByIds?id=1,3,5,6,7 @GetMapping("/findUserByIds") public String findUserByIds(HttpServletRequest request){ String id = request.getParameter("id"); String[] idStr = id.split(","); Integer[] intArray = new Integer[idStr.length]; for (int i=0;i<idStr.length;i++){ intArray[i] = Integer.parseInt(idStr[i]); } System.out.println(intArray); return "Parameter received successfully!!!"; } /** * Servlet Core rules of parameter transfer * http://localhost:8090/findServlet?name="Zhang San“ * Question: where does the String name value come from???? * Core: parameters are taken, not passed * Request process: a request object that returns a response * matters needing attention: * 1.Parameter names must be the same * 2.Disadvantages no matter what kind of data is, it is a String data type and needs to be converted manually * SpringMVC: * The Servlet mechanism is encapsulated internally And it can realize automatic data processing according to the user's parameter type * Type conversion */ @GetMapping("/findServlet") public String findServlet(Integer age){ return "get data:"+age; } /*@GetMapping("/findServlet") public String findServlet(HttpServletRequest request){ String age = request.getParameter("age"); Integer ageInt = Integer.parseInt(age); return "Get data: "+ age; }*/
5.2.3 Preview
Follow the video to understand the installation principle of ElementUi scaffold client
URL: https://www.bilibili.com/video/BV1SU4y1V7Jc/