Mybatis中标签大全

文章目录

一、标签分类

 二、标签总结

1. 基础SQL标签

1.1 查询select

1.2 增删改

1.3 其他基础标签

1.3.1 sql 标签

1.3.2 include 标签

1.3.3 if 标签

1.3.4 别名

2. collection与association标签

3. resultMap标签

4. foreach标签

5. where标签

6. set标签

7. trim标签

8. choose、when、otherwise标签

二、写在后面


一、标签分类

定义SQL语句

  • insert
  • delete
  • update
  • select

 配置关联关系

  • collection
  • association

 配置java对象属性与查询结果集中列名的对应关系

  • resultMap

 控制动态SQL拼接

  • foreach
  • if
  • choose

 格式化输出

  • where
  • set
  • trim

定义常量

  • sql

 其他

  • include

 二、标签总结

1. 基础SQL标签

1.1 查询select

    /**
     * 根据条件查询用户集合
     */
    List<User> selectUsers(@Param("cond")Map<String, Object> map);
    <!-- 返回的是List,resultType给定的值是List里面的实体类而不是list,mybatis会自动把结果变成List -->
    <select id="selectUsers" parameterType="map" resultType="con.it.bean.User">
        select id, username, password, sex, birthday, address from user u
        <where>
            <trim suffixOverrides=",">
                <if test="cond.username != null and cond.username != ''">
                    u.username = #{cond.username},
                </if>
                <if test="cond.sex != null">
                    and u.sex = #{cond.sex},
                </if>
                 <if test="cond.beginTime != null">
                    <![CDATA[  and DATE_FORMAT(u.birthday, '%Y-%m-%d %H:%T:%s') >= DATE_FORMAT(#{beginTime}, '%Y-%m-%d %H:%T:%s'),   ]]>
                </if>
                <if test="cond.endTime != null">
                    <![CDATA[  and DATE_FORMAT(u.birthday, '%Y-%m-%d %H:%T:%s') <= DATE_FORMAT(#{endTime}, '%Y-%m-%d %H:%T:%s'),   ]]>
                </if>
                <if test="cond.address != null and cond.address != ''">
                    and u.addrerss like '%' || #{cond.address} || '%',
                </if>
            </trim>
        </where>
    </select>

1.2 增删改

    <insert id="insert" parameterType="com.it.bean.User">
    
        <!-- 使用序列插入oracle数据库返回主键,MYSQL数据库无需添加selectKey -->
        <selectKey resultType="long" order="BEFORE" keyProperty="id">
            SELECT user_seq.NEXTVAL as id from DUAL
        </selectKey>
        
        insert into User (ID, USERNAME, PASSWORD, SEX, ADRESS, CREATED_BY, CREADTED_DATE)
        values (#{id}, #{username}, #{password}, #{sex}, #{adress}, #{createdBy}, SYSDATE)
    </insert>

1.3 其他基础标签

1.3.1 sql 标签

定义一些常用的sql语句片段

<sql id="selectParam">
    id, username, password, sex, birthday, address
</sql>

1.3.2 include 标签

引用其他的常量,通常和sql一起使用

<select>
    select <include refid="selectParam"></include>
    from user
</select>

1.3.3 if 标签

基本都是用来判断值是否为空,注意Integer的判断,mybatis会默认把0变成 ‘’

<if test="item != null and item != ''"></if>

<!-- 如果是Integer类型的需要把and后面去掉或是加上or-->
<if test="item != null"></if>
<if test="item != null and item != '' or item == 0"></if>

1.3.4 别名

经常使用的类型可以定义别名,方便使用,mybatis也注册了很多别名方便我们使用

<typeAliases>
     <typeAlias type="com.it.bean.User" alias="User"/>
</typeAliases>

2. collection与association标签

collection与association的属性一样,都是用于resultMap返回关联映射使用,collection关联的是集合,而association是关联单个对象

/**
  *问题表
  */
public class Question {
    
    private Long id; //问题id

    private String question; //问题
    
    private Integer questionType; //问题类型
    
    private List<QuestionAnswer> answerList; //问题选项集合
    
    //Getter和Setter省略
}

/**
  *问题选项表
  */
public class QuestionAnswer {
    
    private Long id; //选项id
    
    private Long questionId;  //问题id

    private String answer; //选项
    
    //Getter和Setter省略
}
<!-- 具体可参考下面ResultMap -->
<collection property="answerList" javaType="java.util.List"
                ofType="com.it.bean.QuestionAnswer" column="id" 
                select="setlectQuestionAnswerByQuestionId"/>

3. resultMap标签

 

<!-- 返回关联查询的问题 -->
<resultMap id="detail_result" type="com.it.bean.Question">
    <id column="id" property="id" />
    <result column="question" property="question" />
    <result column="question_type" property="questionType" />
    <collection property="answerList" javaType="java.util.List"
                ofType="com.it.bean.QuestionAnswer" column="id" 
                select="setlectQuestionAnswerByQuestionId"/>
</resultMap>

<!-- 查询问题集 -->
<select id="selectQuestions" parameterType="map" resultMap="detail_result">
    select q.id, q.question, q.question_type 
    from question q 
    <where>
        <if test="cond.id != null">
            q.id = #{cond.id}
        </if>
        <if test="cond.idList != null and cond.idList.size() != 0">
            q.id in 
            <foreach collection="cond.idList" item="id" open="(" separator="," close=")">
                #{id}
            </foreach>
        </if>
    </where>
</select>

<!-- 查询对应问题的答案集 -->
<select id="setlectQuestionAnswerByQuestionId" parameterType="long" resultType="com.it.bean.QuestionAnswer">
    select a.id, a.answer from question_answer a where a.question_id = #{id}
</select>

4. foreach标签

<sql id="base_column">id, question_id, answer</sql>

<!-- oracle的批量插入 -->
<insert id="insertBatchOracle" parameterType="list">
    insert into question_answer ( <include refid="base_column" /> ) 
    select question_answer_seq.NEXTVAL, A.* from (
        <foreach collection="list" item="item" separator="union all">
            select #{item.questionId}, #{item.answer} from dual
        </foreach>
    ) A 
</insert>

<!-- Mysql的批量插入,主键自增 -->
<insert id="insertBatchMysql" parameterType="list">
    insert into question_answer ( <include refid="base_column" /> ) 
    values 
        <foreach collection="list" item="item" open="(" separator="union all" close=")">
            #{item.id}, #{item.questionId}, #{item.answer}
        </foreach>
</insert>

5. where标签

where用来去掉多条件查询时,开头多余的and

    <select id="selectUserList" parameterType="com.it.bean.User" resultType="com.it.bean.User">
        <!-- 引用Sql片段 -->
        select <include refid="selectParam"> from user u
        <where>
            <!--where 可以自动去掉条件中的第一个and-->
            <if test="id != null">
                and u.id = #{id}
            </if>
            <if test="name != null and name != ''">
                and u.name = #{name}
            </if>
        </where>
    </select>

6. set标签

set是mybatis提供的一个智能标记,当在update语句中使用if标签时,如果前面的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号。
没有使用if标签时,如果有一个参数为null,都会导致错误,如下示例:
 

    <update id="updateUser" parameterType="com.it.bean.user">
        update user
        <set>
            <if test="username != null and username != ''">
                username = #{username},
            </if>
            <if test="sex != null and sex == 0 or sex == 1">
                sex = #{sex},
            </if>
            <if test="birthday != null ">  
                birthday = #{birthday},
            </if >  
            <if test="address != null and address != ''">
                address = #{address},
            </if>
            <if test="lastModifiedBy != null and lastModifiedBy != ''">
                last_modified_by = #{lastModifiedBy},
                last_modified_date = SYSDATE,
            </if>
        </set>
        <where>
            id = #{id}
        </where>
    </update>

7. trim标签

prefix:前缀      
prefixoverride:去掉第一个and或者是or
suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)

suffix:后缀
<update id="test" parameterType="com.it.bean.User">
    update user
        <!-- 开头加上set,结尾去除最后一个逗号 -->
        <trim prefix="set" suffixOverrides=",">
            <if test="username!=null and username != ''">
                name= #{username},
            </if>

            <if test="password!=null and password != ''">
                password= #{password},
            </if>

        </trim>
        <where>
            id = #{id}
        </where>
    </update>
    

8. choose、when、otherwise标签

<select id="getUserList" resultType="com.it.bean.User" parameterType="com.it.bean.User">  
    SELECT <include refid="resultParam"></include> FROM User u   
    <where>  
        <choose>  
            <when test="username !=null and username != ''">  
                u.username LIKE CONCAT(CONCAT('%', #{username}),'%')  
            </when >  
            <when test="sex != null">  
                AND u.sex = #{sex}  
            </when >  
            <when test="birthday != null ">  
                AND u.birthday = #{birthday}  
            </when >  
            <otherwise>  
            </otherwise>  
        </choose>  
    </where>    
</select>  

二、写在后面


在网上看了很多标签的解释,但不是很全,我就自己总结了一份,搭配示例更好理解标签的含义,如有什么遗漏或是错误还望多多发言补充,我会继续完善。

注: 关于参数指定jdbcType,是因为当传参为null时候,mybatis无法自动判断类型,就必须要显示指定它的类型,多用于insert中
传入的参数的字段为null对象无法获取对应的jdbcType类型,而报的错误。 
你只要在insert语句中insert的对象加上jdbcType就可以了,修改如下: 
#{menuTitle,jdbcType=VARCHAR} 

 

 

  • 11
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值