Mybatis框架之常用标签学习

常用标签

  1. selectKey标签:在执行某条sql语句之前或者之后进行的查询,主要用于自动生成主键,语法:<selectKey order="BEFORE/AFTER" resultType="返回值类型" keyProperty="映射的实体的属性值">
  2. insert标签:进行插入数据操作。
  3. select标签:进行数据查询操作,主要结合其他标签拼凑查询。
  4. delete标签:进行数据删除操作。
  5. update标签:进行数据的更新操作。
  6. if标签:主要用来进行条件查询或者解决空值插入。具体语法为:<if test="校验条件">sql语句</if>
  7. sql标签:解决重复查询语句,语法:<sql id="唯一标示">sql语句</sql>
  8. include标签:引用,主要和sql标签配合使用。<include refid="sql标签的id"/>
  9. choose标签:主要用来条件查询,类似于switch case语句,用于where语句中。语法:<choose><when test="条件">查询sql</when><otherwise>查询sql</otherwise></choose>
  10. set标签:主要用来进行条件更新。语法:<set><if test="校验条件">字段=值,</if></set>,最后一个if条件不用加逗号。
  11. foreach标签:循环使用,主要属性有:item、index、collection、open、separator、close。item表示集合中每个元素进行迭代时的别名,index表示在迭代过程中每次迭代到的位置,collection表示传递的参数集合,open表示该语句以什么开始,separator表示在每次迭代之间以什么符号作为分隔符,close表示该语句以什么结束,和open对应。
  12. resultMap标签:当数据表中字段的名称和实体的名称不一致时,可以使用此标签进行映射,则在select标签中使用resultMap进行查询。语法:<resultMap type="实体类" id="唯一的标志"><result column="数据表字段" property="实体属性"/></resultMap>

常见问题

  1. 插入空值null的处理方式:①使用jdbcType来进行映射转换;②使用if标签来进行处理
  2. 查询中使用map进行查询时,如果使用id作为map的key值时,如果使用resultMap进行映射,则map的key值类型和实体的类型保持一致,如果使用的resultType进行映射,则id作为map的key值,就要看mybatis框架的封装了,具体可参见以下实例。
  3. 使使 {变量}来进行动态传入前台处理的变量值。使用方法:${variable},在map中使用variable作为key值进行传递值。
  4. 别名:在使用map封装查询结果时,如果使用别名,则map中只能使用别名进行获取数值。
  5. 分页:使用 RowBounds(m,n),其中m表示开始位置,n表示间隔。

实例

标签使用的配置文件:

 <?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="mybatis.commontag">
    <!-- resultMap标签:当实体类和表字段不对应时,将实体类和表字段一一对应起来,默认为一致 -->
    <resultMap type="com.mybatis.entity.User" id="userMap">
        <result column="id" property="id"/>  <!-- column:表中字段,property:实体类属性 -->
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="birthday" property="birthday"/> 
        <result column="address" property="address"/>
        <result column="zipcode" property="zipcode"/>
        <result column="email" property="email"/>
    </resultMap>
    <!-- sql标签:用来解决重复的sql语句  使用别名解决map中取值为大写-->
    <sql id="userField">id "id",username "username",password "password",birthday "birthday",address "address",email "email",zipcode "zipcode"</sql>

    <!-- 使用resultMap进行查询,使用include来引用sql标签 -->
    <select id="selectAllUser" resultMap="userMap">
        select <include refid="userField"/> from user_t
    </select>

    <!-- 使用${}传入sql变量语句 -->
    <select id="selectAllUserByCond" resultType="map" parameterType="map">
        select <include refid="userField"/> from user_t order by ${orderSql}
    </select>

    <!-- 对于非空列,null值插入的两种处理方法 -->
    <!-- 第一种:进行映射数据类型进行处理,使用jdbcType来进行映射 -->
    <insert id="insertNullValueOne" parameterType="map">
        <selectKey order="BEFORE" resultType="java.lang.Long" keyProperty="id">
            select user_t_seq.nextval from dual
        </selectKey>
        insert into user_t(id,username,password,birthday,email,zipcode,address) 
        values(#{id,jdbcType=INTEGER},#{username,jdbcType=VARCHAR},#{password,jdbcType=VARCHAR},#{birthday,jdbcType=DATE},#{email,jdbcType=VARCHAR},#{zipcode,jdbcType=VARCHAR},#{address,jdbcType=VARCHAR})
    </insert>
    <!-- 第二种: 使用if标签来进行判断处理,没有第一种方便-->
    <insert id="insertNullValueTwo" parameterType="map">
        <selectKey order="BEFORE" resultType="java.lang.Long" keyProperty="id">
            select user_t_seq.nextval from dual
        </selectKey>
        <if test="email!=null">
            insert into user_t(id,username,password,birthday,email,zipcode,address) 
        values(#{id},#{username},#{password},#{birthday},#{email},#{zipcode},#{address})
        </if>
        <if test="email==null">
            insert into user_t(id,username,password,birthday,zipcode,address) 
        values(#{id},#{username},#{password},#{birthday},#{zipcode},#{address})
        </if>
    </insert>

    <!-- choose标签:类似于switch case语句,用于select -->
    <select id="useChooseToQuery" resultType="map" parameterType="map">
        select <include refid="userField"/> from user_t where 1=1 
            <choose>
                <when test="username != null"> and username like #{username}||'%'</when>
                <when test="password !=null"> and password like #{password}||'%'</when>
                <otherwise> and birthday is null</otherwise>
            </choose>
    </select>

    <!--set标签:用于条件更新指定的列 -->
    <update id="useSetToUpdate" parameterType="map">
        update user_t
            <set>
                <if test="username != null"> username = #{username},</if>
                <if test="password != null">password = #{password},</if>
                <if test="birthday != null">birthday = #{birthday},</if>
                <if test="address != null">address = #{address},</if>
                <if test="email!=null"> email = #{email},</if>
                <if test="zipcode != null">zipcode = #{zipcode}</if>
            </set>
            <if test="id != null"> where id = #{id}</if>
    </update>
    <!-- foreach标签:主要是sql中的in的体现 -->
    <select id="useForeachToQuery" resultType="map" parameterType="map">
        select <include refid="userField"/> from user_t where id in 
        <foreach collection="idlist" index="currentIndex" open="(" separator="," close=")" item="eachId">
            #{eachId}
        </foreach>
    </select>
</mapper>

测试使用的文件:

package com.mybatis.entity;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.mybatis.util.SqlSessionFactoryUtil;

/**
 * 测试mybatis的常用标签
 * @author Administrator
 *
 */
public class TestCommonTag {
private SqlSession session = null;

    @Before
    public void before(){
        SqlSessionFactory factory = SqlSessionFactoryUtil.getSqlSessionFactory();
        if(factory != null){
            session = factory.openSession();
        }
    }

    //测试resultMap以及sql标签
    @Test
    public void testResultMap(){
        if(session != null){
            System.out.println("------使用List------");
            List<User> lists = session.selectList("mybatis.commontag.selectAllUser");
            for(User user:lists){
                System.out.println("id:" + user.getId() + ",username:" + user.getUsername() + ",password:"+
                        user.getPassword() + ",address:" + user.getAddress() +
                        ",email:" + user.getEmail() + ",zipcode:" + user.getZipcode());
            }
            System.out.println("------使用Map------");
            //在此注意使用id作为map的key值,且使用resultMap则map的key值和实体保持一致,因此必须使用Long型进行遍历,否则无法遍历。
            Map<Long,User> map = session.selectMap("mybatis.commontag.selectAllUser","id");//id作为map的key值
            Set<Long> keys = map.keySet();
            for(Long key:keys){
                User user = map.get(key);
                System.out.println("id:" + user.getId() + ",username:" + user.getUsername() + ",password:"+
                        user.getPassword() + ",address:" + user.getAddress() +
                        ",email:" + user.getEmail() + ",zipcode:" + user.getZipcode());
            }
        }
    }

    //条件查询测试,在加入排序条件后,如果使用map则无法按照顺序来正确查询,使用list可以正确进行排序,且使用别名后,只能使用别名进行查询
    @Test
    public void testConditionQuery(){
        if(session != null){
            //传递变量到sql语句中
            System.out.println("------使用${}传入sql变量语句------");
            Map map = new HashMap();
            map.put("orderSql", "username desc,id desc");
            System.out.println("------使用List------");
            List<Map> lists = session.selectList("mybatis.commontag.selectAllUserByCond",map,new RowBounds(2, 2));//使用分页,查询2、3条记录
            for(Map valueMap:lists){
                System.out.println("id:" + valueMap.get("id") + ",username:" + valueMap.get("username") + ",password:"+
                        valueMap.get("password") + ",address:" + valueMap.get("address") +
                        ",email:" + valueMap.get("email") + ",zipcode:" + valueMap.get("zipcode"));
            }

            System.out.println("------使用Map------");
            //在此注意使用id作为map的key值,没有使用resultMap,只使用resultType=map,则Map的key值为BigDecimal,否则无法遍历。
            Map resultMap = session.selectMap("mybatis.commontag.selectAllUserByCond",map,"id");//id作为map的key值
            Set<BigDecimal> keys = resultMap.keySet();
            for(BigDecimal key:keys){
                Map valueMap =  (Map) resultMap.get(key);
                System.out.println("id:" + valueMap.get("id") + ",username:" + valueMap.get("username") + ",password:"+
                        valueMap.get("password") + ",address:" + valueMap.get("address") +
                        ",email:" + valueMap.get("email") + ",zipcode:" + valueMap.get("zipcode"));
            }
        }
    }


    //空值处理的测试:映射处理空值
    @Test
    public void testReflectDealNullValue(){
        Map map = new HashMap();
        map.put("username", "wangwu");
        map.put("password", "wangwu123");
        map.put("address", "上海市黄浦区南京东路");
        map.put("zipcode", "123453");
        if(session != null){
            session.insert("mybatis.commontag.insertNullValueOne",map);
        }
    }
    //空值处理的测试:使用if标签
    @Test
    public void testIfTagDealNullValue(){
        Map map = new HashMap();
        map.put("username", "wangwu");
        map.put("password", "wangwu123");
        map.put("address", "上海市黄浦区南京东路");
        map.put("zipcode", "123453");
        try {
            map.put("birthday", new SimpleDateFormat("yyyy-MM-dd").parse("1990-04-02"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(session != null){
            session.insert("mybatis.commontag.insertNullValueTwo",map);
        }
    }

    //使用choose标签动态选择
    @Test
    public void testUseChooseToQuery(){
        Map map = new HashMap();
        map.put("password", "li");
        if(session != null){
            List<Map> lists = session.selectList("mybatis.commontag.useChooseToQuery",map);
            for(Map valueMap:lists){
                System.out.println("id:" + valueMap.get("id") + ",username:" + valueMap.get("username") + ",password:"+
                        valueMap.get("password") + ",address:" + valueMap.get("address") +
                        ",email:" + valueMap.get("email") + ",zipcode:" + valueMap.get("zipcode"));
            }
        }
    }

    //使用set标签动态更新
    @Test
    public void testUseSetToUpdate(){
        Map map = new HashMap();
        map.put("id", 23);
        map.put("username", "张三三");
        map.put("password", "zhangsansan123");
        try {
            map.put("birthday", new SimpleDateFormat("yyyy-MM-dd").parse("1993-08-02"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(session != null){
            session.update("mybatis.commontag.useSetToUpdate", map);
        }
    }
    //测试foreach标签
    @Test
    public void testUseForeachToQuery(){
        Map map = new HashMap();
        List list = new ArrayList();
        list.add(11);
        list.add(21);
        list.add(23);
        list.add(25);
        map.put("idlist", list);
        if(session != null){
            List<Map> lists = session.selectList("mybatis.commontag.useForeachToQuery",map);
            for(Map valueMap:lists){
                System.out.println("id:" + valueMap.get("id") + ",username:" + valueMap.get("username") + ",password:"+
                        valueMap.get("password") + ",address:" + valueMap.get("address") +
                        ",email:" + valueMap.get("email") + ",zipcode:" + valueMap.get("zipcode"));
            }
        }
    }

    @After
    public void after(){
        if(session != null){
            session.commit();//session需要commit 否则无法尽心提交
            session.close();
        }
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值