Mybatis - use and configuration

CRUD

namespace

The package name in the namespace should be consistent with the package name of Dao/mapper interface

select

id: is the method name in the corresponding namespace

I personally understand that namespace is the interface implemented, and id is the method of rewriting the interface

resultType: the return value type of sql execution, which is generally in the entity class

parameterType: parameter type

com.xxx.dao.UserMapper(Dao).java

public interface UserMapper{
    // Query user by ID
    User getUserById(int id);
    User addUser(User user);
}

com.xxx.dao.UserMapper(Dao).xml

<mapper namespace="com.xxx.dao.UserMapper">
    <select id="getUserById" parameterType="int" resultType="com.xxx.pojo.User">
    	select * from database.Table name where id = #{id}
    </select>
    <insert id="addUser" parameterType="com.xxx.pojo.User">
    	insert into database.Table name (id, name, pwd) values (#{id}, #{name}, #{pwd})
        <!-- pojo Variable name inside = #{write the variable name in pojo}, which is the same as before -- >
    </insert>
</mapper>

Just write the test class again. Note that the transaction sqlsession must be submitted for addition, deletion, modification and query commit();

MySQL8.0 does not need to commit

mybatisplus Don't write anything

Map

use

int add(Map<String, object> map);
<insert id="add" parameterType="map" >
	insert into database.Table name (id, name, pwd) values (#{xxid}, #{namxxe}, #{pwxxd}) 
    <!-- pojo Variable name inside = #{custom variable name, consistent with the test class} -- >
</insert>
Map<String, Object> map = new HashMap<String, Object>();
map.put("xxid", 5);
map.put("namxxe", "xx");
map.put("pwxxd", "xx");
// In this way, you can learn from different attributes without modifying all attributes at once. Before the map, because the constructor in the User class sets the number of incoming parameters, you must pass all parameters, or you can set individual parameters, but it is not flexible enough
// When the test class passes parameters to the dao layer, all parameters of new user must be present, but map does not
// Ali's JAVA development suggestion is to force the use of map
// And if you use map, you will report an error if the data is transmitted illegally
mapper.add(map);

Fuzzy query

where like "Lee%"

Pass wildcards

where like #{value}

List userList = mapper.getUserLiske("% Li%");

Use wildcards instead of the above operation

where like concat('%', #{value}, '%') / / use # to prevent sql injection

List userList = mapper.getUserLiske("Li");

Configuration resolution

Core profile

myBatis-config.xml, which has order in xml configuration

Environment configurations

MyBatis can be configured to adapt to a variety of environments

Although multiple environments can be configured, only one environment can be selected for each SqlSessionFactory instance.

  • The default environment ID (for example, default = "development").
  • The environment ID defined by each environment element (for example, id = "development").
  • Configuration of the transaction manager (for example: type = "JDBC").
  • Configuration of data source (for example, type = "POOLED").

There are two types of transaction managers in MyBatis (that is, type="[JDBC|MANAGED]")

If you are using Spring + MyBatis, there is no need to configure the transaction manager, because the Spring module will use its own manager to override the previous configuration.

Three built-in data source types (i.e. type="[UNPOOLED|POOLED|JNDI]", default POOLED)

properties

The reference configuration file is implemented through the properties property

These properties can be configured externally and can be replaced dynamically. You can configure these properties either in a typical Java properties file or in a child element of the properties element. [db.properties]

First read the properties specified in the properties element body Finally, read the property passed as a method parameter and overwrite the previously read property with the same name. Then read the property file under the classpath according to the resource attribute in the properties element, or read the property file according to the path specified by the url attribute, and overwrite the previously read property with the same name.

Write dB properties

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!--Import external profile-->
    <properties resource="db.properties">
    	<property name="username" value="dev_user"/>
  		<property name="password" value="F2Fa3!33TYyg"/>
    </properties>
    
    <!--property Attributes in the element body take precedence, and resource If an attribute with the same name is encountered in the import file, it will be overwritten-->

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                  <property name="driver" value="${driver}"/>
                  <property name="url" value="${url}"/>
                  <property name="username" value="${username}"/>
                  <property name="password" value="${password}"/>
    </dataSource>   
        </environment>
    </environments>
</configuration>

1db. The configuration in properties cannot have quotation marks and spaces,

2 some version url links need to use & amp;,

3 when quoting, the key should be filled in correctly

Type aliases

1. Type alias You can set an abbreviated name for a Java type. The full class name is recommended.

<!--Before use-->
resultType="cn.com.mybatis.pojo.User"
<typeAlias alias="user" type="cn.com.mybatis.pojo.User"/>
<!--After use-->
resultType="user"
<typeAliases>
      <typeAlias alias="Author" type="domain.blog.Author"/>
</typeAliases>

2. You can also specify a package name. MyBatis will search for the required Java beans under the package name, scan the packages of entity classes, and add an alias for each entity class. The default alias is the class name of the class, with a lowercase initial

<typeAliases>
      <package name="com.xxx.pojo"/>
</typeAliases>

3. If there is an annotation, the alias is its annotation value. See the following example:

import org.apache.ibatis.type.Alias;
@Alias("author")
public class Author {     ...  }

set up


Lazy loading

Lazy loading The function uses a proxy object, so only when calling the get/set method of the lazy load attribute (or other methods that trigger the lazy load operation) can mybatis know that the lazy load attribute should be loaded at this time.

Lazy loading, in popular terms, is loading on demand. We can do what we need when we need it. Moreover, querying from a single table first and then associating the query from the associated table when necessary can greatly improve the database performance, because querying a single table is faster than associating multiple tables.

The mybatis framework uses javassist to create proxy objects for lazy load objects.

<!-- Enable lazy load configuration -->
<settings>
    <!-- Global settings lazy loading. If set to'false',Then all associated will be initialized and loaded. -->
    <setting name="lazyLoadingEnabled" value="true"/>
    <!-- When set to'true'When, lazy loaded objects may be loaded by any lazy attribute. Otherwise, each property is loaded on demand. -->
    <setting name="aggressiveLazyLoading" value="false"/>
</settings>

Other configurations

plug-in unit

mappers

The Mapper is actually a dynamic proxy object. Entering the execute method of MapperMethod, you can simply find the deletion, update, query and selection methods of SqlSession. From the bottom implementation, let the interface run through the dynamic proxy technology, and then adopt the command mode, Finally, the SqlSession interface method (getMapper() method and Mapper) is used to execute SQL queries (that is, the underlying implementation of Mapper interface method is still implemented by SqlSession interface method)

Register with class file binding:

Interface and Mapper configuration file must have the same name

The interface and mapper configuration files can be in different packages and placed in the same name package mapper or dao under resources. If you want to separate, you only need to create the same package as the interface under resource. Because the compiled class file will be in the same package as xml.

Scan package

<!-- Register all the mapper interface implementations in the package as mappers -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

life cycle

Different scopes and lifecycle categories are crucial because incorrect use can lead to very serious concurrency problems.

SqlSessionFactoryBuilder

Once SqlSessionFactory is created, it is no longer needed. Therefore, the best scope of the SqlSessionFactoryBuilder instance is the method scope (that is, local method variables).

SqlSessionFactory

  • It can be understood as database connection pool
  • Once SqlSessionFactory is created, it should always exist during the operation of the application. There is no reason to discard it or recreate another instance.
  • Rebuilding SqlSessionFactory multiple times is considered a code "bad habit".
  • The simplest is to use singleton mode or static singleton mode.

SqlSession

  • sqlsession is a type of session
  • sqlsession is a connection request from the connection pool.
  • The best scope is the request or method scope. Close when used up, or resources will be occupied.
  • An sqlsession can use its getMapper method multiple times to obtain multiple mapper interface instances. A mapper represents a specific business.

SqlSession principle

Resultmap result mapping set

Resolve conflicts where field names are different from entity class attribute names:

Solution 1: define the alias of the field name in the query sql statement to make the alias of the field name consistent with the attribute name of the entity class, so that the field name of the table can correspond to the attribute name of the entity class one by one. This method solves the mapping relationship between the field name and the attribute name by defining the alias in the sql statement.

Solution 2: map the one-to-one correspondence between field names and entity class attribute names through. This method uses the solution provided by MyBatis to solve the mapping relationship between field names and attribute names.

Solve the problem of inconsistency between attribute name and field name:

  1. Alias: alias on sql query statement: pwd as password

  2. Belongs to Resultmap

Resultmap

Result set mapping: find your own label to map

The design idea of ResultMap is to achieve zero configuration for simple statements. For more complex statements, you only need to describe the relationship between statements.

<!--take User Entity class specified as UserMap-->
< resultMap id="UserMap" type="User">
    <!--column Database fields, property Entity class properties-->
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>
<select id="getUserId" resultMap="UserMap">
	select * from xxx.xx where id = #{id}
</select>

The above statement simply maps all columns to the key of the HashMap, which is specified by the resultType attribute.

Keywords: Mybatis

Added by fert on Sat, 22 Jan 2022 07:09:38 +0200