"Java EE Internet lightweight framework integrated development-SSM framework" reading combing 2: Mybatis (3-5 chapters)

mybatis introduction

The mybaits framework does not shield sql, and sql can be written by developers. And supports dynamic sql function. Allows to assemble sql statements according to different conditions. Mybatis also supports interface-oriented programming. Only interface + xml or annotations are needed to create a mapper through dynamic proxy to perform corresponding operations.

mybatis core components

SqlSessionFactoryBuilder: Create a SqlSessionFactory object through the creator mode. Its life cycle should be limited to the method, and it should disappear after the SqlSessionFactory is created.
SqlSessionFactory: The factory object used to produce SqlSession, and its life cycle should be the same as mybatis.
SqlSession: SqlSession is similar to Connection and represents a database connection resource. Sql statements can be executed through the SqlSession object, transactions can be controlled, and Mapper mappers can be obtained.
Mapper (mapper): Mapper is the most complex component, it consists of an interface and xml files or annotations. He can configure mapping rules, configure sql statements, cache configuration and dynamic sql configuration.

Mybatis configuration

properties

Introduce properties file

<properties resource="路径"/>

Configure directly in xml


<properties>
        <property name="key" value="value"/>
    </properties>

Then it can be referenced by way of ${property name}.

settings

<settings>
        <setting name="" value=""/>
    </settings>

You can set some parameters that affect the operation of mybatis.

Insert picture description here


Insert picture description here

typeAliases

<typeAliases>
        <typeAlias type="全限定类名" alias="别名"/>
    </typeAliases>

You can define an alias for a long object name or a name that is not easy to understand.

TypeHandler type converter

Commonly used type converters have been written in mybatis, and under normal circumstances, we do not need to configure them. Type conversion is to convert java type and jdbc type. The custom type converter needs to implement the TypeHandler interface. Sometimes we use custom type converters when converting enumerated types and jdbcType.

public class MyTypeHandler implements TypeHandler<SEXEnum> {
    //给预编译的sql设置参数
    public void setParameter(PreparedStatement preparedStatement, int i, SEXEnum sexEnum, JdbcType jdbcType) throws SQLException {
        if(sexEnum == SEXEnum.BOY){
            //1代表男性
            preparedStatement.setInt(i,1);
        }else{
            //2代表女性
            preparedStatement.setInt(i,2);
        }
    }
    //根据名字获取
    public SEXEnum getResult(ResultSet resultSet, String s) throws SQLException {
        Integer sex = (Integer) resultSet.getObject(s);
        if (sex == 1){
            return SEXEnum.BOY;
        }else{
            return SEXEnum.GIRL;
        }
    }
    //根据下标获取
    public SEXEnum getResult(ResultSet resultSet, int i) throws SQLException {
        Integer sex = (Integer) resultSet.getObject(i);
        if (sex == 1){
            return SEXEnum.BOY;
        }else{
            return SEXEnum.GIRL;
        }
    }
    //存储过程
    public SEXEnum getResult(CallableStatement callableStatement, int i) throws SQLException {
        Integer sex = (Integer) callableStatement.getObject(i);
        if (sex == 1){
            return SEXEnum.BOY;
        }else{
            return SEXEnum.GIRL;
        }
    }
}

ObjectFactory

The object factory packages the result set into the bean objects we need. The object factory has been defined by mybatis, and we generally don't need to change it.

environments (operating environment)

<environments default="">
        <environment id="">
            <transactionManager type=""></transactionManager>
            <dataSource type="">
                <property name="" value=""/>
            </dataSource>
        </environment>
    </environments>

The operating environment can be configured in environments, and the transaction manager can be configured for transactions. Generally, fill in JDBC. dataSource can be used to configure the data source. type can be used to configure whether to use a connection pool.

Mapper

The mapper is a complex and very important component in mybatis. Most of the time in the development of the persistence layer is configuring the mapper.

Insert picture description here


Among them, the four labels of select insert update delete correspond to the operation of adding, deleting, modifying and checking the database.

Attributes that can be configured in the select tag

Insert picture description here


Insert picture description here


The return value of select needs to be mapped to a bean object. We can perform mapping through automatic mapping, camel case mapping, and resultmap.
Automatic mapping is enabled by default. Camel case mapping needs to be configured in settings. The resultmap method needs to configure the mapped objects by themselves and introduce them in select.
When passing parameters in the interface, you can pass in objects or ordinary variables. If you want to pass in multiple parameters, you need to use @Param to configure.

insert

The return value of insert is an integer, which represents the number of rows of data to be operated on.
Sometimes the primary key is automatically generated by the database, but we need to get this generated gradually after inserting the data. We can configure it by configuring UserGeneratedKey and KeyProperty. KeyProperty represents which property is backfilled into.
You can also get the primary key through the selectKey tag.

<insert id="" parameterType="" useGeneratedKeys="true" keyProperty="id">
        
    </insert>
<insert id="" parameterType="" >
        <selectKey keyProperty="id" order="AFTER">
            select Last_insert_id();
        </selectKey>
    </insert>

Update and Delete

Update and delete are relatively simple, and the return value after execution is an integer, which represents the number of data rows changed.

sql

The sql tag can customize a reusable sql segment, and then quote it where needed. You can also introduce attributes through ${}.

<sql id="selectAll">
        select * from ${table}
    </sql>
    <select id="" parameterType="" resultType="" >
        <include refid="selectAll">
            <property name="table" value="user"/>
        </include>
    </select>

resultMap

Cascade operations can also be configured in resultMap.

<resultMap id="student" type="com.User" >
        <!--主键-->
        <id property="id" column="id"/>
        <!--普通属性映射-->
        <result property="name" column="name"/>
        <result property="sex" column="sex"/>
        <!--如果User没有无参构造器就需要配置这个-->
        <!--<constructor>
            <arg name="" column=""/>
        </constructor>-->
        <!--一对一级联 column参数-->
        <association property="school" column="id" select="com.set.FindSchoolByUid"/>
        <!--一对多级联-->
        <collection property="friends" column="id" select="com.set.FindFriendsByUid" />
        <!--鉴别器 使用sex属性进行鉴别-->
        <discriminator javaType="String" column="sex">
            <case value="男" resultMap="boy"></case>
            <case value="女" resultMap="girl"></case>
        </discriminator>
    </resultMap>
    <resultMap id="boy" type="" extends="student">
        <association property="boyObject" column="id" select=""/>
    </resultMap>
    <resultMap id="girl" type="" extends="student">
        <association property="girlObject" column="id" select=""/>
    </resultMap>

Many-to-many cascading can be realized by two one-to-many cascading.
Moreover, the N+1 problem is prone to occur in the case of cascading, that is, redundant data is queried. At this time, we can solve this problem by configuring lazy loading

    <settings>
        <!-- 打开延迟加载的开关默认为false,将所有的级联都设置为延迟加载 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 这个相当于是层级的延迟加载。默认为true,如果为true的话,会将查询对象的下一级的级联也查询出来-->
        <setting name="aggressiveLazyLoading" value="false" />
        
    </settings>

You can set fetchType="eager" at the cascade operation to turn off lazy loading.

Cache

Stored procedure