
一、动态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">
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.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查询
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)【重点
】
内存中的一块存储空间,服务于某个应用程序,旨在将频繁读取的数据临时保存在内存中,便于二次快速访问。
无缓存:用户在访问相同数据时,需要发起多次对数据库的直接访问,导致产生大量IO、读写硬盘的操作,效率低下 |
---|
![]() |
有缓存:首次访问时,查询数据库,将数据存储到缓存中;再次访问时,直接访问缓存,减少IO、硬盘读写次数、提高效率 |
---|
![]() |
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.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注解操作
通过在接口中直接添加MyBatis注解,完成CRUD。
@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);
网友评论