How mybatis Realizes mapper Proxy Mode

  • 2021-09-24 22:44:24
  • OfStack

Continue to review mybtis tonight
Take querying a single piece of data according to id value as an example
Write SqlMapConfig. xml files


<configuration> 
<!--  Use mybatis Required data source and transaction configuration, if the subsequent integration spring After that, it will no longer be needed  --> 
<environments default="development"> 
<!--  Configuring data sources and transactions  --> 
<environment id="development"> 
<!--  Configure transaction management , Give transaction management to mybatis Management  --> <transactionManager type="JDBC" /> 
<!--  Configure the data source  --> 
<dataSource type="POOLED">
 <property name = "driver" value = "com.mysql.jdbc.Driver" /> 
 <property name="url" value="jdbc:mysql://localhost:3306/db_shop? useUnicode=true&amp;characterEncoding=utf-8"/>
  <property name="username" value="root"/> <property name="password" value=""/>
   </dataSource>
    </environment> 
    </environments>
     <!--  Loading **.xml Configuration file  --> 
     <mappers> 
     <mapper resource="product.xml"/>
</mappers> 
</configuration>

Write bleeding model object: Product, preferably field name and field name in database 1 straight


/**** <p>Title: Product</p> * 
<p>Description:  Commercial blood loss model </p> *
 @author Alon *
  @date 2020 Year 9 Month 27 Day   Afternoon 6:51:57 
  * @version 1.0 */ 
 public class Product {
  private int p_id;
   private String name; 
   private int p_number;
    private double price; 
    private String add_time;
     public Product(int p_id, String name, int p_number, double price, String add_time) { 
     super();
      this.p_id = p_id; 
      this.name = name; 
      this.p_number = p_number; 
      this.price = price; 
      this.add_time = add_time; 
      }public Product() { 
        super();
       }
       public int getP_id() { 
       return p_id; }
       public void setP_id(int p_id) { 
       this.p_id = p_id; }public String getName() { return name; }
       public void setName(String name) { this.name = name; }
       public int getP_number() { 
       return p_number; }
       public void setP_number(int p_number) { this.p_number = p_number; }
       public double getPrice() { return price; }
       public void setPrice(double price) { this.price = price; }
       public String getAdd_time() { return add_time;
}
public void setAdd_time(String add_time) { this.add_time = add_time; }
@Override 
public String toString() { 
return "Product [p_id=" + p_id + ", name=" + name + ", p_number=" + p_number + ", price=" + price + ", add_time=" + add_time + "]"; } }

Writing sql. xml: product. xml for a single mapping


<?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">
 <!--  Mapped sql Documents  namespace: Namespace, which can be understood as putting part of the sql Statement for isolation. To the back mapper There will be more proxy methods   Add an important role  --> <mapper namespace="test"> 
 <!--select: Represents the query statement to execute  id: Object for this query statement 1 A name, only 1 Adj. ,java Gets or sets the use to be invoked in the. 
  parameterType: Data type of input parameter  
  resultType: The data type of the output parameter, 1 Bind into model Object of  #{value}: Indicates that it is used with placeholders 1 Sample, which is used to accept the input parameter value.  --> <select id="findById" parameterType="java.lang.Integer" resultType="com.woniuxy.model.Product">
   SELECT * FROM t_product WHERE p_id = #{value}
    </select>
     </mapper>

Write java code to test, execute sql statement and get results


/**** <p>Title: MybatisDemo1</p> *
 <p>Description:  Object for querying data demo</p> *
  @author Alon 
  * @date 2020 Year 9 Month 27 Day   Afternoon 7:05:32 
  * * @version 1.0 */ 
  * public class MybatisDemo1 {
  *  public static void main(String[] args) throws IOException { 
  * new MybatisDemo1().queryById(); }
  * public void queryById() throws IOException {
  *  //1 , read to SqlMapConfig.xml Stream of files  String path = "SqlMapConfig.xml"; 
  * InputStream config = Resources.getResourceAsStream(path);
// Create a session factory , At the same time, SqlMapConfig.xml The data inside is put into the factory  SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config); 
// Open a session  SqlSession sqlSession = factory.openSession(); /**  No. 1 1 Parameters: Which to execute sql Statement, 1 General namespace .id Value  *  No. 1 2 Parameters: Incoming padding #{value} Gets or sets the value of the parameter passed in.  */ 
Object obj = sqlSession.selectOne("test.findById", 1); System.out.println(obj); } }

Perform fuzzy query: query multiple result sets


<!--  In the original xml You can configure it in the file, you don't need to create it, and the previous one has already been in SqlMapConfig.xml It is matched in the document   Set  --> <select id="queryByName" parameterType="java.lang.String" resultType="com.woniuxy.model.Product"> SELECT * FROM t_product WHERE name like "%${value}%" </select> public void queryByName() throws Exception
{
 String path = "SqlMapConfig.xml"; // Get stream object  InputStream config = Resources.getResourceAsStream(path); // Get the session factory  SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config); // Open a session  SqlSession sqlSession = factory.openSession(); /**  Because the execution result has multiple statements, you must use the selectList */ List<Object> list = sqlSession.selectList("test.queryByName", " Wang Tsai "); // Iteration  System.out.println(list); 
}

Add statement


<!--  Add 1 Bar data  parameterType: The data type of the passed parameter can be used as a blood loss model object.  --> 
<insert id="insertProduct" parameterType="com.woniuxy.model.Product"> 
INSERT INTO t_product(name,p_number,price) value(#{name},#{p_number},# {price}); 
</insert>

/**
**<p>Title: insert</p> 
*<p>Description:  Add data </p> 
* @throws Exception 
* */ public void insert() throws Exception{ String path = "SqlMapConfig.xml"; 
* // Get stream object  
* InputStream config = Resources.getResourceAsStream(path); // Get the session factory 
*  SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config); 
* // Open a session  
* SqlSession sqlSession = factory.openSession();
*  Product prod = new Product();
*  prod.setName(" Sprite "); 
* prod.setP_number(10); 
* prod.setPrice(3.0);
*  int row = sqlSession.insert("test.insertProduct", prod); System.out.println(row); sqlSession.commit(); sqlSession.close(); }

mapper agent to explain the way to add, delete, change and check (key)
Step 1: Create the corresponding Mapper interface, and the previous dao interface 1
Step 2: Write the corresponding xxmapper. xml configuration file. Have requirements
1) namespace in the mapper tag: It must be written as the full pathname of the corresponding Mapper interface
2) id in the sql statement: Must correspond to the name of the corresponding method in the interface.
3) parameterType in sql statement: It must be corresponding to the formal parameter data type 1 of the method in the interface
4) resultType in sql statement: Must be corresponding to the return value data type 1 of the method in the interface
Step 3: Load the written **mapper. xml file in the SqlMapConfig. xml file
Step 4: Write the implementation class and test it directly here
Detailed explanation of alias and mapper mapping
Setting Alias
In the mybatis configuration file, the alias exists 1 straight away, but in fact there are already 1 default aliases in the framework. For example
Alias for java. lang. String: String, java. lang. Integer: int
In development, the corresponding names of parameterType and resultType in mapper. xml configuration files need to be written
The full path of model, and it is reused many times. You can choose to give this path an alias of 1. Replace more complicated ones with aliases
Full pathname
Configured as a scan package
Custom POJO Class (Focus)
Custom POJO class, 1 generally refers to advanced query, in the desired data and incoming conditions are no longer 1 table, through the table created by the loss of blood
The model model can no longer meet the requirements of passing in parameters. At this time, you need to use the custom POJO class
Because a blood loss model can no longer meet the requirements of query input parameters, it is expanded to create an UserCustom class, in
Face contains user object declarations and userInfo object declarations

The above is the mybatis implementation of mapper proxy mode in detail, more information about mybatis mapper proxy mode please pay attention to other related articles on this site!


Related articles: