MyBatis 第三篇

 一、动态SQL【重点

MyBatis的映射文件中支持在基础SQL添加一些逻辑操作,并动态拼接成完整的SQL之后再执行,以达到SQL复用、简化编程的效果

1.1 <sql>

public List<User> findAll(); 

<mapper namespace="com.qf.dao.UserDao">

    <sql id="BaseSql">
        select id,name,password
    </sql>

    <!--配置查询所有-->
    <select id="findAll" resultType="user">
        <!-- 引入sql片段 -->
        <include refid="BaseSql"></include>
        FROM t_user
    </select>
</mapper>

1.2 < if >

public User findByUser(User user);
<select id="findByUser" resultType="com.qf.entity.User">
    <include refid="BaseSql"></include>
    FROM t_user
    where
    <if test="name!=null and name!=''">
        name=#{name}
    </if>
    <if test="password!=null">
        password=#{password}
    </if>
</select>

1.3 < where >

public User findByUser(User user);
<select id="findByUser" resultType="com.qf.entity.User">
    <include refid="BaseSql"></include>
    FROM t_user
    <where>   <!-- WHERE,会自动忽略前后缀(如:and | or) -->
        <if test="name!=null">
            name=#{name}
        </if>
        <if test="password!=null">
            and password=#{password}
        </if>
    </where>
</select>   

1.4 < set >

public Integer UpdateByUser(User user);
<update id="UpdateByUser">
    update t_user
    <set>
        <if test="name!=null">
            name=#{name},
        </if>
        <if test="password!=null">
            password=#{password}
        </if>
    </set>
    <where>
        <if test="id!=null">
            id=#{id}
        </if>
    </where>
</update>

1.5 < trim >

< trim prefix="" suffix="" prefixOverrides="" suffixOverrides="" >代替< where > 、< set >

<select id="findByUser" resultType="com.qf.pojo.User">
    <include refid="BaseSql"></include>
    FROM t_user
    <trim prefix="WHERE" prefixOverrides="AND|OR"> <!-- 增加WHERE前缀,自动忽略前缀 -->
        <if test="name!=null">
            and name=#{name}
        </if>
        <if test="password!=null">
            and password=#{password}
        </if>
    </trim>
</select>
<update id="UpdateByUser">
    update t_user
    <trim prefix="SET" suffixOverrides=","> <!-- 增加SET前缀,自动忽略后缀 -->
        <if test="name!=null">
            name=#{name},
        </if>
        <if test="password!=null">
            password=#{password},
        </if>
    </trim>
    <where>
        <if test="id!=null">
            id=#{id}
        </if>
    </where>
</update>

1.6 < foreach >

通过多个id查询 public List<User> findUserByIds(List<Integer> ids); public List<User> findUserByIds(Integer [] ids);

<!-- 多个id查询 -->
<!--collection="list"-->
<select id="findUserByIds" resultType="user">
    <include refid="BaseSql"></include>
    from t_user
    <where>
        id in
        <foreach collection="array" open="(" close=")" separator="," item="id">
            #{id}
        </foreach>
    </where>
</select>
参数描述取值
collection容器类型list、array、map
open起始符(
close结束符)
separator分隔符,
index下标号从0开始,依次递增
item当前项任意名称(循环中通过 #{任意名称} 表达式访问)

二、缓存(Cache)【重点


内存中的一块存储空间,服务于某个应用程序,旨在将频繁读取的数据临时保存在内存中,便于二次快速访问。

  2.1 一级缓存

SqlSession级别的缓存,同一个SqlSession的发起多次同构查询,会将数据保存在一级缓存中。

@Test
public void testfindById()throws Exception {
​
    InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    SqlSessionFactory factory = builder.build(in);
    SqlSession session = factory.openSession();
    //---------------------------------------------
    UserDao userDao = session.getMapper(UserDao.class);
​
    //证明SqlSession级别的一级缓存存在
    User user1 = userDao.findById(1);
​
    //当调用SqlSession的修改,添加,删除,commit(),close()等方法时也会清空一级缓存。
    //session.clearCache();//清空缓存
    //session.close();
    //session = factory.openSession();
    //userDao = session.getMapper(UserDao.class);
​
    User user2 = userDao.findById(1);
​
    System.out.println(user1 == user2);
    //---------------------------------------------
    session.close();
    in.close();
}

2.2 二级缓存

SqlSessionFactory级别的缓存,同一个SqlSessionFactory构建的SqlSession发起的多次同构查询,会将数据保存在二级缓存中。

2.2.1 开启全局缓存

< settings >是MyBatis中极为重要的调整设置,他们会改变MyBatis的运行行为,其他详细配置可参考官方文档。

<configuration>
    <properties .../>
    
    <!-- 注意书写位置 -->
    <settings>
        <setting name="cacheEnabled" value="true"/> <!-- mybaits-config.xml中开启全局缓存(默认开启) -->
    </settings>
  
    <typeAliases></typeAliases>
</configuration>

2.2.2 指定Mapper缓存

<mapper namespace="com.qf.dao.UserDao">
    <cache /> <!-- 指定缓存 -->
​
    <!-- 查询单个对象 -->
    <select id="findById" resultType="com.qf.pojo.User">
        select id,name,password FROM t_user where id=#{id}
    </select>
</mapper>
@Test
public void testfindById2() throws Exception {
​
    //1.读取配置文件
    InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
    //2.创建SqlSessionFactory工厂
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    SqlSessionFactory factory = builder.build(in);
    //3.使用工厂生产SqlSession对象
​
    SqlSession sqlSession1 = factory.openSession();
    UserDao dao1 = sqlSession1.getMapper(UserDao.class);
    User user1 = dao1.findById(1);
    System.out.println(user1);
    sqlSession1.close();//一级缓存消失
​
    SqlSession sqlSession2 = factory.openSession();
    UserDao dao2 = sqlSession2.getMapper(UserDao.class);
    User user2 = dao2.findById(1);
    System.out.println(user2);
    sqlSession2.close();
​
    in.close();
}

三、注解


3.1 MyBatis注解操作

通过在接口中直接添加MyBatis注解,完成CRUD。

1.mybatis-config.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <!--  引入外部文件  -->
    <properties resource="db.properties"></properties>

    <!--   配置别名-->
<!--    <typeAliases>-->
<!--        <package name="com.qf.pojo"/>-->
<!--    </typeAliases>-->

    <!--配置环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!-- 配置数据源(连接池) -->
            <dataSource type="com.qf.datasource.DruidDataSourceFactory">
                <property name="driverClassName" value="${db.driverClassName}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper class="com.qf.dao.UserDao"></mapper>
    </mappers>
</configuration>

2.UserDao接口

package com.qf.dao;

import com.qf.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserDao {

   //使用注解的时候,要在mybatis-config.xml文件中配置<mapper class="com.qf.mapper.UserDao"></mapper>
  //且没有UserDao.xml文件

   //查询所有
    @Select("select * from t_user")
    List<User> findAll();

    //根据编号查询
    @Select("select * from t_user where id = #{id}")
    User findById(Integer id);

    //添加用户
    @Insert("insert into t_user(name,password) values(#{name},#{password})")
    void addUser(User user);

    //修改用户
    @Update("update t_user set name = #{name},password = #{password} where id = #{id}")
    void updateUser(User user);

    //删除用户
    @Delete("delete from t_user where id = #{id}")
    void deleteUser(Integer id);

    //获取总记录数
    @Select("select count(id) from t_user")
    Integer findTotalCount();

    //获取分页数据
    /*
    * 说明:
     1.当你使用了使用@Param注解来声明参数时,如果使用 #{} 或 ${} 的方式都可以,
     * 当你不使用@Param注解来声明参数时,必须使用使用 #{}方式。如果使用 ${} 的方式,会报错。
    2,不使用@Param注解
     不使用@Param注解时,最好传递 Javabean。在SQL语句里就可以直接引用JavaBean的属性,
    * 而且只能引用JavaBean存在的属性。
    * */
    @Select("select * from t_user limit #{first},#{second}")
    List<User> findPageData(@Param("first") Integer first,@Param("second") Integer second);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小yu别错过

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值