mybatis学习——动态查询、动态修改

一、动态定义

所谓的动态就是条件不确定,如淘宝选购条件
mybatis学习——动态查询、动态修改_第1张图片


二、查询

局部文件配置

    
    <select id="getComDynamic" resultType="map" parameterType="map">
        SELECT *FROM computer
        <where>
            <if test="name!=null">
                name=#{name}
            if>
            <if test="neicun!=null">
                AND neicun=#{neicun}
            if>
            <if test="price!=null">
                AND price=#{price}
            if>
            <if test="cpu!=null">
                AND cpu=#{cpu}
            if>
        where>
    select>

java方法

// 动态查询
    @Test
    public void getComDynamic() throws Exception {
        SqlSession sqlSession = openMybatis();
        Map<String, Object> commap = new HashMap<>();
        commap.put("name", "联想");
        commap.put("price", "2000");
        commap.put("neicun", "4");
        commap.put("cpu", "i5");
        List<Map<String, Object>> map = sqlSession.selectList("com.ComputerDao.getComDynamic", commap);
        for (Map<String, Object> map2 : map) {
            System.out.println(map2);
        }
    }

三、修改

局部配置文件


    <update id="dynamicUpdate">
        UPDATE computer
        <set>
            <if test="neicun!=null">
                neicun=#{neicun},
            if>
            <if test="price!=null">
                price=#{price},
            if>
            <if test="cpu!=null">
                cpu=#{cpu},
            if>
            name=#{name}
        set>
        WHERE name=#{name}
    update>

java方法

// 动态修改
    @Test
    public void dynamicUpdate() throws Exception {
        SqlSession sqlSession = openMybatis();
        Map commap = new HashMap<>();
        commap.put("name", "联想");
        commap.put("price", "8000");
        commap.put("cpu", "i9");
        sqlSession.update("com.ComputerDao.dynamicUpdate", commap);
        sqlSession.commit();
    }

四、类似 IF……ELSE….语句

    
    <select id="">
        <choose>
            <when test="">when>
            <otherwise>otherwise>
        choose>
    select>

你可能感兴趣的:(mybatis)