1. Mybatis hump mapping
1.1 case demonstration
Problem Description: there are many scenarios where hump rules are used in work. However, if each attribute needs to be encapsulated manually, it is cumbersome. Therefore, the framework should provide the function of automatic mapping
1.2 description of hump rules
- Official website description:
- Setting settings
<!--to configure settings information--> <settings> <!--Turn on hump mapping rules--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <typeAliases> <!--type: POJO Object path alias: For current POJO Object alias--> <!--<typeAlias type="com.jt.pojo.User" alias="User"/>--> <!--Set alias package --> <package name="com.jt.pojo"/> </typeAliases>
- Hump rule mapping description
<!--Query user information and open hump mapping rules resultType: 1.Applicable to single table query,At the same time, the attribute name should be the same as the field. 2.If attributes and fields meet hump naming rules,After starting hump mapping, have access to resultType resultMap: 1.Use if fields are inconsistent 2.Used in multi table Association query. 3.If hump mapping rule is enabled, Then the automatically mapped attributes can be omitted,It is best to identify the primary key 4.If hump rule mapping is used,When mapping encapsulated objects is required(one-on-one/One to many),By default.Hump rule failure. have access to: autoMapping="true" Hump mapping is required. 5.One to one by default,One to many will not automatically complete hump rule mapping. Configuration required autoMapping="true"To map automatically --> <select id="getAll" resultMap="getEmpMap"> select e.emp_id,e.emp_name, d.dept_id,d.dept_name from emp e,dept d where e.dept_id = d.dept_id </select> <resultMap id="getEmpMap" type="Emp" autoMapping="true"> <id column="emp_id" property="empId"/> <!--Automatic mapping of other attributes--> <!--Implement department mapping--> <association property="dept" javaType="Dept" autoMapping="true"> <id column="dept_id" property="deptId"/> </association> </resultMap>
2. Mybatis caching mechanism
2.1 cache concept
If a large number of the same requests query the database, the database needs to execute repeated sql for many times, so the concurrency pressure is high and the query efficiency is low. If the cache mechanism is introduced, the query efficiency of users can be greatly improved
2.2 Mybatis provides caching mechanism
There is a level 2 cache in Mybatis
The L1 cache sqlSession executes multiple queries within the same sqlSession. The cache is valid. The L1 cache is on by default
Level 2 cache SqlSessionFactory. Using the same factory, different sqlsessions created can realize data sharing (caching mechanism). Level 2 cache is also enabled by default
2.3 L1 cache test
Conclusion: if the same SqlSession is used to perform multiple database operations, the cache is effective. sql is executed only once
@Test public void testCache(){ SqlSession sqlSession = sqlSessionFactory.openSession(); EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class); List<Emp> list1 = empMapper.getAll(); List<Emp> list2 = empMapper.getAll(); List<Emp> list3 = empMapper.getAll(); sqlSession.close(); }
2.4 L2 cache test
2.4.1 specify L2 cache
Syntax: specify cache tags in the respective xml mapping files
2.4.2 L2 cache test
Note: the L2 cache cannot take effect until sqlSession is closed
//Test L2 cache @Test public void testCache2(){ SqlSession sqlSession1 = sqlSessionFactory.openSession(); EmpMapper empMapper = sqlSession1.getMapper(EmpMapper.class); List<Emp> list1 = empMapper.getAll(); sqlSession1.close(); //sqlSession must be closed after use. Otherwise, the L2 cache will not take effect //Create different sqlsessions using the same SqlSessionFactory SqlSession sqlSession2 = sqlSessionFactory.openSession(); EmpMapper empMapper2 = sqlSession2.getMapper(EmpMapper.class); List<Emp> list2 = empMapper2.getAll(); sqlSession2.close(); }
2.4.3 precautions
If you need to use L1 / L2 cache, the POJO object must implement the serialization interface. Otherwise, the data cannot be cached
Schematic serialization rules:
3. Spring boot integrates Mybatis
3.1 create project
3.2 modify pom.xml file
Description: add dependency information to a new project
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <!--Introducing plug-ins lombok automatic set/get/Construction method plug-in --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--mybatis Dependent package--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!--jdbc Dependent package--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies>
3.3 code structure
3.4 spring boot integration with Mybatis
3.4.1 edit application.yml
#Configure port number server: port: 8090 #Manage data sources spring: datasource: #Use of high version driver 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 #Set user name and password username: root password: root #Spring boot integrates Mybatis mybatis: #Specify alias package type-aliases-package: com.jt.pojo #Scan the mapping file under the specified path mapper-locations: classpath:/mybatis/mappers/*.xml #Turn on hump mapping configuration: map-underscore-to-camel-case: true
3.4.2 submit Mapper interface to container management
- Manage objects through @ Mapper annotations
@Mapper //The Mapper interface is managed by the Spring container public interface UserMapper { List<User> findAll(); }
- Through package scanning, manage the mapper interface, edit the main startup class, and specify the package scanning path
@SpringBootApplication //Scan the interface management object of mapper according to the specified package path @MapperScan("com.jt.mapper") public class SpringbootSsmApplication { public static void main(String[] args) { SpringApplication.run(SpringbootSsmApplication.class, args); } }
3.4.3 Mybatis unit test case
@SpringBootTest class SpringbootSsmApplicationTests { @Autowired //Inject the specified object private UserMapper userMapper; //IDEA compilation tips do not affect execution /** * Test spring boot integration with Mybatis */ @Test public void testfindAll(){ List<User> userList = userMapper.findAll(); System.out.println(userList); } }
3.5 description of Mapper interface object
Explanation:
- Give the interface to the spring container for management, and spring will dynamically select and create the proxy object according to the class type. Finally, give the proxy object to the spring container for management
- Use of proxy objects
3.5.1 introduction to agency mode
3.5.1.1 JDK dynamic agent
characteristic:
- The agent must have an interface
- By default, if there is an interface, JDK dynamic proxy is used
6.5.1.2 CGLIB dynamic agent
characteristic:
- A proxy object can be created for a delegate, whether or not it has an interface
- The proxy object is a subclass of the target object. Inheritance relationship
Conclusion:
- If there is an interface in Spring, JDK proxy is used by default. If there is no interface, CGLIB proxy is used by default
- After spring 5, cglib is used when creating proxy objects from its own interface objects
3.6 SSM framework cases
3.6.1 business requirements
User access URL: http://localhost:8090/findAll
Return value: JSON string of List
3.6.2 framework diagram
3.6.3 level code implementation
3.6.4 editing UserController
@RestController //@ResponseBody converts the list collection into json public class UserController { @Autowired private UserService userService; /** * URL: http://localhost:8090/findAll * Parameter: None * Return value: List < user > */ @RequestMapping("/findAll") public List<User> findAll(){ return userService.findAll(); } }
3.6.5 editing UserService
@Service public class UserServiceImpl implements UserService{ @Autowired private UserMapper userMapper; @Override public List<User> findAll() { return userMapper.findAll(); } }
3.6.5 editing UserService
@Service public class UserServiceImpl implements UserService{ @Autowired private UserMapper userMapper; @Override public List<User> findAll() { return userMapper.findAll(); } }
3.6.6 editing UserMapper
mapper interface
public interface UserMapper { List<User> findAll(); }
mapper mapping file
<mapper namespace="com.jt.mapper.UserMapper"> <!--Alias packages must be configured--> <select id="findAll" resultType="User"> select * from demo_user </select> </mapper>
3.6.7 page effect display
4. Framework code case exercise
4.1 query data according to ID
4.1.1 requirements description
Query database by Id
URL: http://localhost:8090/findUserById?id=1
Return value: User object
4.1.2 editing UserController
/** * Requirements: http://localhost:8090/findUserById?id=1 * Parameter receiving: id=1 * Return value: User object */ @RequestMapping("/findUserById") public User findUserById(Integer id){ return userService.findUserById(id); }
4.1.3 editing UserService
@Override public User findUserById(Integer id) { return userMapper.findUserById(id); }
4.1.4 edit UserMapper
//Only one of the annotation and mapping files can be selected @Select("select * from demo_user where id = #{id}") User findUserById(Integer id);
4.1.5 page effect display
4.2 query data according to age and sex
4.2.1 business requirements
URL: http://localhost:8090/findUserByAS
Return value: List collection encapsulation
4.2.2 editing UserController
/** * URL Address: http://localhost:8090/findUserByAS?age=18&sex= female * Parameter: age = 18 sex = female * Return value: List < set > * Parameter receiving: if there are multiple parameters and the parameter name is consistent with the attribute name, object receiving can be used */ @RequestMapping("/findUserByAS") public List<User> findUserByAS(User user){ return userService.findUserByAS(user); }
4.2.3 editing UserService
@Override public List<User> findUserByAS(User user) { return userMapper.findUserByAS(user); }
4.2.4 editing UserMapper
##4.3 RestFul parameter transfer
4.3.1 business requirements
Note: it is required to modify the data according to the id
restFul request path: http://localhost:8090/updateById/1/ Black bear essence / 3000 / male
4.3.2 editing UserController
/** * URL: http://localhost:8090/updateById/1/Black bear essence / 3000 / male * Parameters: 4 * Return value: "modified successfully!!!" * restFul Structural parameter analysis {attribute name} * Parameter reception: * 1. A single parameter is received using @ PathVariable Integer id * 2. If multiple parameters are received, use the function automatically provided by the object mvc */ @RequestMapping("/updateById/{id}/{name}/{age}/{sex}") public String updateById(User user){ userService.updateById(user); return "User modified successfully"; }
4.3.2 editing UserService
//After spring integrates mybatis, transactions are automatically committed @Override public void updateById(User user) { userMapper.updateById(user); }
4.3.2 editing UserMapper
@Update("update demo_user set name=#{name},age=#{age},sex =#{sex} where id=#{id}") void updateById(User user);