"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


Introduce properties file

<properties resource="路径"/>

Configure directly in xml

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

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


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

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

Insert picture description here

Insert picture description here


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

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> {
    public void setParameter(PreparedStatement preparedStatement, int i, SEXEnum sexEnum, JdbcType jdbcType) throws SQLException {
        if(sexEnum == SEXEnum.BOY){
    public SEXEnum getResult(ResultSet resultSet, String s) throws SQLException {
        Integer sex = (Integer) resultSet.getObject(s);
        if (sex == 1){
            return SEXEnum.BOY;
            return SEXEnum.GIRL;
    public SEXEnum getResult(ResultSet resultSet, int i) throws SQLException {
        Integer sex = (Integer) resultSet.getObject(i);
        if (sex == 1){
            return SEXEnum.BOY;
            return SEXEnum.GIRL;
    public SEXEnum getResult(CallableStatement callableStatement, int i) throws SQLException {
        Integer sex = (Integer) callableStatement.getObject(i);
        if (sex == 1){
            return SEXEnum.BOY;
            return SEXEnum.GIRL;


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=""/>

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.


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.


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 id="" parameterType="" >
        <selectKey keyProperty="id" order="AFTER">
            select Last_insert_id();

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.


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}
    <select id="" parameterType="" resultType="" >
        <include refid="selectAll">
            <property name="table" value="user"/>


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"/>
            <arg name="" column=""/>
        <!--一对一级联 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>
    <resultMap id="boy" type="" extends="student">
        <association property="boyObject" column="id" select=""/>
    <resultMap id="girl" type="" extends="student">
        <association property="girlObject" column="id" select=""/>

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

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

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


Stored procedure