• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Concept: myBatis is an ORM framework of persistence layer, that is, a semi-finished software, which solves the problem of generality in software development, simplifies the development steps and improves the development efficiency.

ORM: Object Relational Mapping, which maps objects in a program to data recorded in a table.

Function:

1. Support custom SQL, stored procedures and advanced mapping

2. Encapsulate native JDBC operations, almost eliminating redundant JDBC code

3. Support XML configuration SQL and annotation configuration SQL, and automatically complete ORM operations, return the results.

What are the disadvantages of JDBC? :

1. There is a lot of redundant code

2. Manually obtain the connection and close it

3. Encapsulate a ResultSet

4. Low efficiency and no cache

To optimize the

A. Set database connection parameters to db.properties

  --<properties resource="db.properties"></properties>
  --<property name="driver" value="${driver}"/>
  
Copy the code

B. the connection pool to replace druid – define connection pool factory, UnpooledDataSourceFactory inheritance

Provides a constructor in which the dataSource of the parent class is assigned a value

— In mybatis main configuration file, point to custom dataSourceFactory by type

C. Configure the entity category name

Method 1: Configure based on XML

<typeAliases> // Define an alias for a single entity class. Type: type alias: alias <! --<typeAlias type=" com.qf.entity.sale "alias=" Sale" ></typeAlias>--> <package name="com.qf.entity"/> </typeAliases>Copy the code

Method 2: Annotation-based configuration

  @Alias("sale1")
  public class Sale {} 
Copy the code

D. The attribute name of the entity class is inconsistent with that of the field

Method 1: Define an alias

Method 2: Define a resultType as a Map

   <select id="findById2" resultType="map/int/double/javaBean">
    select * from sale where id=#{id}
   </select>
   
Copy the code

Method 3: Customize a resultMap to specify the mapping between field names and attribute names

<select id="findById3" resultMap="saleMap"> select * from sale where id=#{id} </select> <resultMap id="saleMap" type="sale1"> <id column="id" property="id"></id> <result column="prodName" property="name"></result> <! --<result column="qty" property="qty"></result>--> </resultMap>Copy the code