Framework Project Learning - Mybatis Framework

Mybatis Framework

Annotation Development for MyBatis

MyBatis's mapping configuration supports annotations to configure sql statements in addition to xml configuration
Question: Why there are xml configurations and annotated configurations

Answer: MyBatis's annotation development is more concise, just need to annotate the corresponding SQL statement's annotation on the corresponding function method, directly connect the XxxMapper.xml mapping file can be omitted

Annotation development itself is a trend in Java configuration, and later on learning SpringBoot, you will find that all are configured with pure annotations

MyBatis provides the following notes for mapping file configuration

@Select Query Data Comment
@Insert insert data comment
@Delete Delete Data Annotation
@Update Modify Data Annotation
@Options option configuration
@Results Manual Mapping Configuration
Mapping information configuration for a specific column in @Result:@results

Case Code

package cn.xc.mybatis.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import cn.xc.mybatis.pojo.User;

public interface UserMapper {
	
	@Insert("insert into user (name,age,password)values(#{name},#{age},#{password})")
	int insert(User user);

	//Single Line Query
	@Select("select id t_id,name t_name,password t_password,age t_age  from user where id = #{id}")
	@Results({
		@Result(id = true,column = "id",property = "id"),
		@Result(column = "t_name",property = "name"),
		@Result(column = "t_password",property = "password"),
		@Result(column = "t_age",property = "age")
	})
	User selectByPrimaryKey(Integer id);
	
	//Multiline query
	@Select("select id t_id,name t_name,password t_password,age t_age  from user")
	@Results({
		@Result(id = true,column = "id",property = "id"),
		@Result(column = "t_name",property = "name"),
		@Result(column = "t_password",property = "password"),
		@Result(column = "t_age",property = "age")
	})
	List<User> selectList();
	
	//Delete operation
	@Delete("delete from user where id = #{id}")
	int deleteByPrimaryKey(Integer id);
	
	//update operation
	@Update("update user set name = #{name},password=#{password},age = #{age} where id = #{id}")
	int updateByPrimaryKey(User user);
}

Configuration of Annotation Mapping

<mappers>
		<!-- Configuration Mapping File -->
		<!-- Configure Individual xml Mapping File -->
		<!-- <mapper resource="cn/xc/mybatis/mapper/UserMapper.xml"/> -->

		<!-- Configure a single mapping interface -->
		<mapper class="cn.xc.mybatis.mapper.UserMapper" />
	</mappers>

Method Multiparameter Pass Using - @Param Annotation

Mybatis does not support passing in multiple parameters by default. Only one parameter can be passed in.

The so-called incoming parameter specification is a Mybatis operation
The incoming parameters of ().
Scenario 1: Encapsulate these parameters into an object (JavaBean/Map) and pass them in.
Option 2: Set a @Param annotation support for parameters and unify the types of multiple parameters

Question: Why not support multiple parameters?
Because before Java syntax 1.7, it was not possible to get the parameter names of methods through reflection.

Solution annotated with @Param parameter

Case Code

package cn.xc.mybatis.mapper;

import java.util.Map;

import org.apache.ibatis.annotations.Param;

import cn.xc.mybatis.pojo.User;

public interface UserMapper {
	/**
	 * Simulate login operation
	 * @param user User object encapsulated with account password
	 * @return User object encapsulated by query results
	 */

	User login(@Param("username") String name,@Param("pwd") String password);
	/**
	 * Simulate login operation
	 * @param user Map collection encapsulated with account password
	 * @return User object encapsulated by query results
	 */

	User login1(Map<String, Object> map);
}

Test Code

package cn.xc.mybatis.test;

import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import cn.xc.mybatis.mapper.UserMapper;
import cn.xc.mybatis.pojo.User;
import cn.xc.mybatis.utils.MyBatisUtil;

public class UserMapperTest {
	
	@Test
	public void testLogin() throws Exception {
		//1. Create SqlSession object
		SqlSession session = MyBatisUtil.openSession();
		//2. Create a proxy object for the UserMapper mapping interface (the interface cannot create objects directly, the underlying creates proxy objects)
		UserMapper userMapper = session.getMapper(UserMapper.class);
		
		//3. Execute login method
		User user = userMapper.login("admin", "123");
		
		System.out.println(user);
		
		//4. Close Session
		session.close();
	}

	@Test
	public void testLogin1() throws Exception {
		//1. Create SqlSession object
		SqlSession session = MyBatisUtil.openSession();
		//2. Create a proxy object for the UserMapper mapping interface (the interface cannot create objects directly, the underlying creates proxy objects)
		UserMapper userMapper = session.getMapper(UserMapper.class);
		
		//3. Execute login method
		Map<String, Object> map = new HashMap<>();
		map.put("username", "Look crazy");
		map.put("pwd", "123");
		User user = userMapper.login1(map);
		
		
		System.out.println(user);
		
		//4. Close Session
		session.close();
	}

}

Differences between #{} and ${}

Two OGNL syntaxes are supported in the MyBatis framework
#{}
${}

#{} PreparedStatement class based on JDBC, SQL statement parameters use? Placeholder, dynamic setting of parameters at run time, but? Cannot be used as table name.
The SQL statement of the precompiled statement object can only operate on DML and DQL statements, not DDL statements

1. #{} means to set a precompiled parameter, which is a parameter to?, so if you can't use #{} without a fixed table name, you can only use ${}

2.KaTeX parse error: Expected'EOF', got'#'at position 27:...Splice parameters into SQL statements. And{] is used instead. So {} is not safe.
3. KaTeX parse error: Expected'EOF', got'#'at position 14: {} can only get the value of the parameter pool, while #{} can get the parameter value of the method, or...{} Get the value of the parameter, which must be accompanied by @Param
Do not use ${} if it is not necessary

Question: So what's the use?A: Note that the original table name of the JDBC-based interface is not usable?Can only be used for incoming parameters.What is the use of {} when the operation involves data that is not a parameter such as table names? A: Note that the original table name of the JDBC-based interface is not usable?Can only be used for incoming parameters. What is the use if the operation involves nonparametric data such as table names?A: Note that the original table name of the JDBC-based interface is not usable?Can only be used for incoming parameters.You need to use {} if the operation involves non-parametric data such as table names

Delete case code

public interface UserMapper {
	
	/**
	 * Delete the specified table name from the database dynamically
	 * @param tableName Table Name
	 * @return
	 */
	int dropTable(@Param("tableName")String tableName);
}

<?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">
 <!-- Mapping Configuration
 	namespace : Namespace, in general, a unique identification name for each mapping file
  -->
<mapper namespace="cn.xc.mybatis.mapper.UserMapper">
	
	<!-- 
		//Use #{} Cannot use table name operation 
	 -->
	<delete id="dropTable" parameterType="String">
		<!-- drop table #{tableName} -->
		drop table ${tableName}
	</delete>
</mapper>

Printing effect

Use #{}

Database tables cannot be deleted using this method

Use ${}

summary

Basic use of MyBatis persistence framework

  1. Why study a framework?
    (1) Previous similar functionality, what are the drawbacks in writing code, and what are the changes in development
    (2) For example: all operations of native JDBC are handled by the developer himself, which is very cumbersome
  2. Find a framework that can solve such problems
    (1) Persistent Layer Solutions
    (1) MyBatis - the mainstream of current enterprises
  1. Semi-automatic frame
    a. Developers can customize SQL statements, but they are more flexible without writing to the framework
    (2) Hibernate - Early projects use more
  2. Full automatic framework
    a. Direct manipulation of objects, developers have no direct control over sql statements
    (3) A persistent API for the official exit of JPA Java
  3. Implemented by the Hibernate framework
    ④ SpringData-JPA
  4. Supports multiple types of data persistence solutions
    a. Relational databases (MySQL, Oracle)
    b. Non-relational databases (NoSQL, MongDB, Redis)
    c. Operating large data frameworks
    _jdbctemplate of Spring framework
  5. A feature of the Spring framework, but a little stronger than jdbc, which simply encapsulates JDBC
    (2) Web Tier Solution - Servlet is not usable
    (1) SpringMVC - a module (component) of the direct Spring framework - the mainstream of the enterprise
    (2) Struts 2-used a lot in the past few years, with serious bug s
    3. Struts - Old
  1. MyBatis Framework Learning Program
    (1) Understanding the characteristics of frameworks
    (2) Introduction to Framework Cases
    1. Direct reference to official documents - first-hand materials
  1. A coding base is required
    (2) Forum Blog
    3. Teachers'Teaching
  1. Specific learning steps
    (1) Framework execution process
    1. Perform illustrative analysis on the framework
    (2) Details of the distribution - Preparation of the environment
    1. Create project import dependency packages
    Prepare the main configuration file mybatis-config.xml
  1. Configure four elements of database connection
    (3) Write the MyBatisUtil tool class to encapsulate common code
  2. Read of Configuration File - SqlSessionFactory Object Creation
  3. Provides methods for returning SqlSession session action objects
    (3) Introduction cases
    1. Create entity Pojo object User corresponding to operation table
    (2) The interface file UserMapper.java for creating table operations
    (3) Create mapping file UserMapper.xml corresponding to interface
    (4) Introduction of UserMapper.xml mapping file into main configuration file
    _Coding
  4. Write specific additions and deletions in interfaces
  5. Functional label for mapping file write correspondence method
    a.
    b. Tags have attributes, and the way attributes are configured and interfaces follow certain mapping rules
    a) Method return type is the same as resultType type
    b) Method parameters and properties parameterType are the same
    c) Method name and id execute identically
    _Write test code
  6. All operations must have a SqlSession object
    A. Create a SqlSession that is directly available through the MyBatisUtil tool
  7. Create UserMapper Proxy Object
  8. Execute CRUD (add delete check) specific method
    (4) Detailed learning configuration for MyBatis framework
    1. Main Configuration Details Configuration
  9. alias
  10. Reading database configuration files
    (2) Manual mapping of MyBatis result set
    (5) Annotation configuration for MyBatis
    ① @Insert @Update @Delete @Select
    (2) Method Multi-parameter Comment@Param
    (6) Differences between #{} and ${}

Tags: Mybatis Session xml Java

Posted on Tue, 10 Sep 2019 18:29:51 -0700 by madrazel