分享

MyBatis笔记

 笑笑兔 2023-08-16 发布于天津

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。

简单易学、灵活能够将sql和代码分离,提高可维护性。

1、resultMap结果集映射

    <!--结果接映射-->
    <resultMap id="UserMap" type="User">
        <!--column数据库中的字段    property实体类的属性 -->
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>


    <select id="getUserById"  parameterType="int" resultMap="UserMap">
        select * from mybatis.user where id = #{id}
    </select>

2、@Param参数注解

接口所有普通参数,尽量都加上,尤其是多个参数传递的时候。

    //查询一个用户
    User queryUserById(@Param("id") int id);

3、动态sql(where if)

        
    <sql id="if-title-author">
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </sql>

    <select id="queryBlogIF" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <include refid="if-title-author"></include>
        </where>

    </select>

where if语句where标签中,如果有返回值就会插入一个where语句,如果返回的内容是 and或or开头,就会剔除掉where。

4、动态sql(where-choose-when-otherewise)

只执行一个满足的条件,类似java 的switch

    //Choose-when-otherwise
    List<Blog> queryBlogChoose(Map map);
        
     <select id="queryBlogChoose" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <choose>
                <when test="title != null">
                    title = #{title}
                </when>
                <when test="author != null">
                    and author = #{author}
                </when>
                <otherwise>
                    and views = #{views}
                </otherwise>
            </choose>
        </where>
    </select>

5、动态sql(where-foreach)

下面这个语句相当于:select * from blog where 1=1 and(id=1 or id=2 or id=3);

    //查询第一二三号记录的博客
    List<Blog> queryBlogForeach(Map map);
        
     <select id="queryBlogForeach" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id = #{id}
            </foreach>
        </where>
    </select>

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多