mybits annotations

Keywords: SQL xml Mybatis Java

I. Simple annotations to mybatis
Key commentaries:
@ Insert: Insert sql, exactly the same as xml insert sql
@ Select: Query sql, exactly the same as xml select sql grammar
@ Update: Update sql, exactly the same as xml update sql syntax
@ Delete: Delete sql, exactly the same as xml delete sql
@ Param: Participation
@ Results: Results SET
@ Result: Results

1.bean Domain Model

package cn.xm.exam.bean.common;

import java.util.Date;

import org.apache.struts2.json.annotations.JSON;
/**
 * Query people over 55 years old ()
 * @author QiaoLiQiang
 * @time 2018 January 25, 2001, 4:03:02 p.m.
 */
public class Message {
    private String messageid;

    private String name;

    private String idcode;

    private String sex;

    private Date birthday;

    private String emptype;

    private String isdispose;

    public String getMessageid() {
        return messageid;
    }

    public void setMessageid(String messageid) {
        this.messageid = messageid == null ? null : messageid.trim();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getIdcode() {
        return idcode;
    }

    public void setIdcode(String idcode) {
        this.idcode = idcode == null ? null : idcode.trim();
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }
    @JSON(format="yyyy-MM-dd")
    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getEmptype() {
        return emptype;
    }

    public void setEmptype(String emptype) {
        this.emptype = emptype == null ? null : emptype.trim();
    }

    public String getIsdispose() {
        return isdispose;
    }

    public void setIsdispose(String isdispose) {
        this.isdispose = isdispose == null ? null : isdispose.trim();
    }

    @Override
    public String toString() {
        return "Message [messageid=" + messageid + ", name=" + name + ", idcode=" + idcode + ", sex=" + sex
                + ", birthday=" + birthday + ", emptype=" + emptype + ", isdispose=" + isdispose + "]";
    }
    
}

2.Mapper interface definition:

MessageCustomMapper. Java (last five method annotation implementations)

package cn.xm.exam.mapper.common.custom;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import cn.xm.exam.bean.common.Message;

/**
 * Message mapper
 * 
 * @author QiaoLiQiang
 * @time 2018 January 25, 2001, 4:07:45 p.m.
 */
public interface MessageCustomMapper {
    /**
     * Query people over 55 years of age according to the type of employees
     * 
     * @return
     * @param empType:Employee type: 0 short committees, 1 internal
     * @throws SQLException
     */
    public List<Message> getMessageByEmptype(String empType) throws SQLException;

    /**
     * Modify the status of the message (set to read 1)
     * 
     * @param messageId
     *            Message ID
     * @return
     * @throws SQLException
     */
    public int updateMessageStatusByMessageId(String messageId) throws SQLException;

    /**
     * Test annotations use Mybatis
     */
    
    @Insert(" insert into message values (#{messageid,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{idcode,jdbcType=CHAR}, #{sex,jdbcType=VARCHAR}, #{birthday,jdbcType=DATE}, #{emptype,jdbcType=VARCHAR},#{isdispose,jdbcType=VARCHAR})")
    public int insertIntoByAnnotation(Message message) throws SQLException;
    
    @Select("select * from message where messageid = #{messageId}")
    public Message getMessageById(@Param("messageId")String messageId)throws SQLException;
    
    @Update("update message set name=#{name} where messageid=#{messageid}")
    public int updateMessageById(Message message)throws SQLException;
    
    @Select("select * from message where messageid = #{messageId}")
    public Map getMessageMapById(@Param("messageId")String messageId)throws SQLException;
    
    @Delete("delete from message where messageid = #{messageId}")
    public int deleteByMessageId(@Param("messageId")String messageid)throws SQLException;
    

}

MessageCustomMapper. XML (partial implementation only)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.xm.exam.mapper.common.custom.MessageCustomMapper">
    <!-- Query unread messages, displaying 6 items at a time -->
    <select id="getMessageByEmptype" parameterType="string"
        resultType="cn.xm.exam.bean.common.Message">
        select * from message where empType=#{value} and isDispose='0' limit 0,6
    </select>
    <!-- according to ID Setting Message Status -->
    <update id="updateMessageStatusByMessageId">
    update message set isDispose='1' where messageid = #{value}
    </update>
</mapper>

3. The tests are as follows:

package cn.xm.exam.test.daoTest;

import java.sql.SQLException;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.xm.exam.bean.common.Message;
import cn.xm.exam.mapper.common.custom.MessageCustomMapper;

/**
 * mybatis Annotation test
 * 
 * @author QiaoLiQiang
 * @time 2018 March 10, 2000, 3:47:40 p.m.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/application*")
public class MybatisAnnotationTest {

    @Autowired
    private MessageCustomMapper messageCustomMapper;
    
    @Test
    public void testAdd() throws SQLException{
        Message message = new Message();
        message.setSex("1");
        message.setMessageid("001");
        message.setName("Zhang San");
        int result = messageCustomMapper.insertIntoByAnnotation(message);
        System.out.println(result);
    }
    @Test
    public void testSelect() throws SQLException{
        Message result = messageCustomMapper.getMessageById("001");
        System.out.println(result);
    }
    @Test
    public void testUpdate() throws SQLException{
        Message message = new Message();
        message.setSex("2");
        message.setMessageid("001");
        message.setName("Li Si");
        int result = messageCustomMapper.updateMessageById(message);
        System.out.println(result);
    }
    
    @Test
    public void testSelectMap() throws SQLException{
        Map result = messageCustomMapper.getMessageMapById("001");
        System.out.println(result);
    }
    @Test
    public void testDelete() throws SQLException{
        int result = messageCustomMapper.deleteByMessageId("001");
        System.out.println(result);
    }
}

Result:

(1) TesAdd method:

(2) TesSelect method:

(3) TesUpdate method:

(4) TesSelectMap method: (Test return type is Map)

{sex=1, name = Lisi, message id = 001}

(5) TesDelete method:

1

II. Dynamic SQL

The corresponding relationship is as follows.

@Insert : @InsertProvider
@Select : @SelectProvider
@Update : @UpdateProvider
@Delete : @DeleteProvider

Four provider annotation identifiers use dynamic SQL, using a grammatical format:

@UpdateProvider(type = UserProvider.class, method =

How to use dynamic SQL:

public class UserProvider {

    /**
     * udpate
     * @param UserDO userDO
     * @return
     */
    public String updateSQL(final UserDO userDO) {
        return new SQL() {
            {
                UPDATE("t_user");
                SET("gmt_modified = now()");
                if (userDO.getUserName() != null) {
                    SET("user_name = #{userName}");
                }
                WHERE("id = #{id}}");
            }
        }.toString();
    }
}

So it is more convenient for dynamic SQL to write SQL statements in XML.

The knowledge points mentioned in this article are comparatively basic. If you need to have a deeper understanding of the official document or, look at the source code.

Summary:
1. How to choose XML and annotations? Different people have different habits of coding. XML and annotation have their own advantages and disadvantages. xml's shortcomings: when model attributes change, it is necessary to change from DO to DAO to xml. Imagine that XML has advantages too. SQL fragments are easy to reuse, grammar is approachable, unlike annotations, to construct a dynamic statement, and to build a class. And when you need to construct a paragraph of SQL to be referenced in many places, annotation seems powerless to repeat the same SQL fragment, and the code becomes redundant. At this time, XML must be used to extract common use. Mybatis is annotated in Tucao, is that annotation not useless? No, mybatis is suitable for scenarios with frequent changes in model attributes, because it can combine reflection, and regular matching dynamically constructs SQL. It can be said that the advantages of mybatis annotations make up for the shortcomings of xml. They complement each other~

Posted by Paddy on Sat, 27 Jul 2019 00:30:52 -0700