0
点赞
收藏
分享

微信扫一扫

java基础-day49-Myba03

亿奇学 2021-09-29 阅读 59
基础知识

一、动态SQL【重点


1.1 < sql >

<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 >

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

1.3 < where >

<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 >

<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 >

<select id="findByUser" resultType="com.qf.entity.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查询 -->
<!--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)【重点


无缓存:用户在访问相同数据时,需要发起多次对数据库的直接访问,导致产生大量IO、读写硬盘的操作,效率低下

有缓存:首次访问时,查询数据库,将数据存储到缓存中;再次访问时,直接访问缓存,减少IO、硬盘读写次数、提高效率

2.1 一级缓存

  • 注意:无需任何配置,默认开启一级缓存。
@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 二级缓存

  • 注意:在sqlSession.commit()或者sqlSession.close()之后生效。
2.2.1 开启全局缓存
<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.entity.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();
}

2.3 延迟加载

延迟加载
    MyBatis中的延迟加载,也称为懒加载,是指在进行表的关联查询时,按照设置延迟规则推迟对关联对象的select查询。例如在进行一对多查询的时候,只查询出一方,当程序中需要多方的数据时,mybatis再发出sql语句进行查询,这样子延迟加载就可以的减少数据库压力。MyBatis的延迟加载只是对关联对象的查询有迟延设置,对于主加载对象都是直接执行查询语句的。

三、注解


3.1 MyBatis注解操作

@Select("select * from user where id = #{id}")
public User findById(Integer id);

@Select("select * from user")
public List<User> findAll();

@Insert("insert into user(username) values( #{username} )")
public void add(User user);

@Update("update user set username = #{username} where id = #{id}")
public void update(User user);

@Delete("delete from user where id = #{id}")
public void delete(Integer id);

//获取总记录数
@Select("select count(id) from user")
public Integer getTotalCount();

//获取分页数据
@Select("select * from user limit #{first},#{second}")
public List<User> findPageData(@Param("first") Integer first,@Param("second") Integer second);
举报

相关推荐

Java基础day03

java基础-day03-变量

java基础-day53-Spring03

day03-前端基础

Vue基础Day03

Linux基础day03

day49-git

0 条评论