Basic usage MyBatis annotations ways: MyBatis Series (five)

1. @Select comment

1.1 Use Sql statement to set the alias way

Suppose now that there is a demand: According id information query role. How to use the annotation way to achieve it?

First, a method of adding the interface SysRoleMappper:

@Select({"SELECT id,role_name roleName,enabled,create_by createBy,create_time createTime ","FROM sys_role ","WHERE id = #{id}"})
SysRole selectById(Long id);

The above code can be written in the following format:

@Select({"SELECT id,role_name roleName,enabled,create_by createBy,create_time createTime FROM sys_role WHERE id = #{id}"})
SysRole selectById(Long id);

Two or more ways are transmitted in the form of an array of strings, we can also use a direct transfer of a string:

@Select("SELECT id,role_name roleName,enabled,create_by createBy,create_time createTime FROM sys_role WHERE id = #{id}")
SysRole selectById(Long id);

Use annotation mode also need to consider the issue of Java attribute table fields and field mapping, there are three main ways to use annotations ways.

A first type is provided by an alias Sql statement, the above code is used in this way.

1.2 mapUnderscoreToCamelCase configuration

Before we open the new mybatis-config.xml file src / main / resources directory, add the following configuration:

<settings>
    <!--其他配置-->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

After the open configuration, MyBatis will automatically mapped according to "underline turn hump" rule, is about to be automatically converted to the database column role_name property roleName.

In this case, the above code can be modified to:

@Select("SELECT id,role_name,enabled,create_by,create_time FROM sys_role WHERE id = #{id}")
SysRole selectById(Long id);

Although the format may also be written as follows, but is not recommended for such use:

@Select("SELECT * FROM sys_role WHERE id = #{id}")
SysRole selectById(Long id);

1.3 Use resultMap way

In xml, we used to configure the mapping resultMap:

<resultMap id="sysUserMap" type="com.zwwhnly.mybatisaction.model.SysUser">
    <id property="id" column="id"/>
    <result property="userName" column="user_name"/>
    <result property="userPassword" column="user_password"/>
    <result property="userEmail" column="user_email"/>
    <result property="userInfo" column="user_info"/>
    <result property="headImg" column="head_img" jdbcType="BLOB"/>
    <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
</resultMap>

In the annotation mode, annotated @Results a configuration corresponding to the mapping:

@Results({
        @Result(property = "id", column = "id", id = true),
        @Result(property = "roleName", column = "role_name"),
        @Result(property = "enabled", column = "enabled"),
        @Result(property = "createBy", column = "create_by"),
        @Result(property = "createTime", column = "create_time")
})
@Select("SELECT id,role_name,enabled,create_by,create_time FROM sys_role WHERE id = #{id}")
SysRole selectById2(Long id);

The code is simple to explain:

1) @Results corresponding annotation tag in the xml resultMap

2) @Result xml tag corresponds to the result of

3) @Result(property = "id", column = "id", id = true)corresponds to the xml<id property="id" column="id"/>

Some people may ask, in my xml, set to resultMap an id, so I can reuse the resultMap, and in the notes, the support?

With this question, let's try to modify the code under:

@Results(id = "roleResultMap", value = {
        @Result(property = "id", column = "id", id = true),
        @Result(property = "roleName", column = "role_name"),
        @Result(property = "enabled", column = "enabled"),
        @Result(property = "createBy", column = "create_by"),
        @Result(property = "createTime", column = "create_time")
})
@Select("SELECT id,role_name,enabled,create_by,create_time FROM sys_role WHERE id = #{id}")
SysRole selectById2(Long id);

It was found that the code compilation error, can not find the id attribute.

Press Ctrl + B, the source @Results found as follows:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Results {
    Result[] value() default {};
}

We can see from the source, this annotation has no id attribute, you do not have to repeat the mapping plus we each approach?

Of course the answer is no, but in MyBatis 3.3.0 and previous versions, the annotation defined @Results can not be shared, you need to write it again on each method. But from MyBatis 3.3.1 version, @ Results annotation adds an id attribute, set the id attributes, you can reference the same @Results configured by the id attribute.

Before read several blog readers may know, we just use the MyBatis version is 3.3.0, it just does not support setting the id attribute, ha ha.

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.3.0</version>
</dependency>

MyBatis modified version 3.3.1 (if not set, then automatically imported changes required manual point Import Changes):

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.3.1</version>
</dependency>

At this time will find that originally compiled the above code can be compiled by the error.

@Results source at this time is as follows, compared to the previous codes, adds the id attribute:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Results {
    String id() default "";

    Result[] value() default {};
}

How does that refer to this @Results comment? Consider the following code:

@ResultMap("roleResultMap")
@Select("SELECT * FROM sys_role")
List<SysRole> selectAll();

Description: When used with the XML mode, id value may also be referenced herein in XML resultMap id attribute value element.

In order to make the space will not be too long, I will not put the unit test code and output logs of these three methods, I believe that seeing the first few blog readers can already write their own unit test code, you can also refer to the source text at the end Download address at source.

2. @Insert comment

2.1 does not need to return to the main key

XML and uses almost the same way, the code is as follows:

@Insert({"INSERT INTO sys_role(id, role_name, enabled, create_by, create_time) ",
        "VALUES (#{id},#{roleName},#{enabled},#{createBy},#{createTime,jdbcType=TIMESTAMP})"})
int insert(SysRole sysRole);

2.2 Back increment primary key

To return to the auto-increment primary key database, as follows:

@Insert({"INSERT INTO sys_role(role_name, enabled, create_by, create_time) ",
        "VALUES (#{roleName},#{enabled},#{createBy},#{createTime,jdbcType=TIMESTAMP})"})
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUseGeneratedKeys(SysRole sysRole);

And XML in use almost @Options(useGeneratedKeys = true, keyProperty = "id")equivalent to the XML useGeneratedKeys="true" keyProperty="id".

2.3 Non-increment primary key return

In the previous blog, we know that selectKey support both primary keys increment of the database, such as MySql, also supports the primary key does not increment the database, such as Oracle, written in XML is this:

<selectKey keyColumn="id" resultType="long" keyProperty="id" order="AFTER">
    SELECT LAST_INSERT_ID()
</selectKey>

Then use the annotation way how to achieve it? Code as follows:

@Insert({"INSERT INTO sys_role(role_name, enabled, create_by, create_time) ",
        "VALUES (#{roleName},#{enabled},#{createBy},#{createTime,jdbcType=TIMESTAMP})"})
@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyColumn = "id", keyProperty = "id", resultType = Long.class, before = false)
int insertUseSelectKey(SysRole sysRole);

before = false equivalent XML in order = "AFTRE", which is configured MySql database.

before = true equivalent XML in order = "BEFORE", which is to configure the Oracle database.

Note: Different databases statement of values ​​will be different, values ​​above apply to MySql database, to pay attention to modify when using other types of databases.

3. @Update comment

XML and uses almost the same way, the code is as follows:

@Update({"UPDATE sys_role ", "SET role_name = #{roleName},enabled = #{enabled},create_by=#{createBy}, ",
        "create_time=#{createTime,jdbcType=TIMESTAMP} ", " WHERE id=#{id}"})
int updateById(SysRole sysRole);

4. @Delete comment

XML and uses almost the same way, the code is as follows:

@Delete("DELETE FROM sys_role WHERE id = #{id}")
int deleteById(Long id);

5. Provider comment

MyBatis provides 4 Provider annotations are @ SelectProvider, @ InsertProvider, @ UpdateProvider and @DeleteProvider.

We understand, for example under @SelectProvider Provider to use annotations.

First, a new category in the following packet com.zwwhnly.mybatisaction.mapper:

package com.zwwhnly.mybatisaction.mapper;

import org.apache.ibatis.jdbc.SQL;

public class SysPrivilegeProvider {
    public String selectById(final Long id) {
        return new SQL() {
            {
                SELECT("id,privilege_name,privilege_url");
                FROM("sys_privilege");
                WHERE("id = #{id}");
            }
        }.toString();
    }
}

This code can also be written as follows:

public String selectById(final Long id) {
    return "SELECT id,privilege_name,privilege_url FROM sys_privilege WHERE id = #{id}";
}

And add the following methods in the interface SysPrivilegeProvider:

@SelectProvider(type = SysPrivilegeProvider.class, method = "selectById")
SysPrivilege selectById(Long id);

Finally, a new test class SysPrivilegeMapperTest at com.zwwhnly.mybatisaction.mapper package under src / test / java:

package com.zwwhnly.mybatisaction.mapper;

import com.zwwhnly.mybatisaction.model.SysPrivilege;
import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.Test;

public class SysPrivilegeMapperTest extends BaseMapperTest {
    @Test
    public void testSelectById() {
        SqlSession sqlSession = getSqlSession();

        try {
            SysPrivilegeMapper sysPrivilegeMapper = sqlSession.getMapper(SysPrivilegeMapper.class);
            SysPrivilege sysPrivilege = sysPrivilegeMapper.selectById(1L);

            Assert.assertNotNull(sysPrivilege);
            Assert.assertEquals("用户管理", sysPrivilege.getPrivilegeName());
        } finally {
            sqlSession.close();
        }
    }
}

Run the test code, the test passes, outputting the log follows:

DEBUG [main] - ==> Preparing: SELECT id,privilege_name,privilege_url FROM sys_privilege WHERE (id = ?)
DEBUG [main] - ==> Parameters: 1(Long)

TRACE [main] - <== Columns: id, privilege_name, privilege_url

TRACE [main] - <== Row: 1, user management, / users

DEBUG [main] - <== Total: 1

6. Source and reference

Source Address: https://github.com/zwwhnly/mybatis-action.git , welcome to download.

Liuzeng Hui "MyBatis from entry to the master."

The original is not easy, if that article can learn something, like a welcome point, a commentary on, off a note, this is my greatest motivation insist on writing.

If you are interested, please add my micro letter: zwwhnly , waiting for you to talk technology, workplace, work and other topics (PS: I am a programmer struggle in Shanghai).

Published 34 original articles · won praise 107 · views 20000 +

Guess you like

Origin blog.csdn.net/zwwhnly/article/details/103022631