10.MyBatis的动态SQL
10.5.trim标签
trim标签可以代替where标签、set标签
- mapper
//修改public void updateByUser2(User user);
<update id="updateByUser2" parameterType="User">update user<!-- 增加SET前缀,忽略,后缀 --><trim prefix="SET" suffixOverrides=","><if test="birthday!=null">birthday=#{birthday},</if><if test="sex!=null and username != '' ">sex=#{sex},</if><if test="address!=null and username != '' ">address=#{address},</if></trim>where id=#{id}</update>
insert 用法
void addUser(User user);
<insert id="addUser" parameterType="user">INSERT INTO user<!--trim标签一定要包括if标签,作用:prefix:加上前缀,“(”suffix:加上后缀,“)”prefixOverrides:去除多余的前缀内容suffixOverrides:去除多余的后缀内容,“,”--><trim prefix="(" suffix=")" suffixOverrides=","><if test="username!=null and username!=''">username,</if></trim><trim prefix="VALUES(" suffix=")" suffixOverrides=","><if test="username!=null and username!=''">#{username},</if></trim></insert>
10.6.foreach标签
foreach标签的常见使用场景是集合进行遍历
- mapper
//批量删除public void deleteUserByIds(@Param("ids") List<Integer> ids);//批量添加public void insertUsers(@Param("userList") List<User> userList);
//批量删除public void deleteUserByIds(@Param("ids") List<Integer> ids);//批量添加public void insertUsers(@Param("userList") List<User> userList);
- 测试
@Testpublic void testDeleteUserByIds(){UserDao userDao = sqlSession.getMapper(UserDao.class);List<Integer> ids = new ArrayList();ids.add(50);ids.add(64);ids.add(67);userDao.deleteUserByIds(ids);}@Testpublic void testInsertUsers(){UserDao userDao = sqlSession.getMapper(UserDao.class);long start = System.currentTimeMillis();List<User> userList = new ArrayList<>();for(int i = 0 ;i < 10000; i++) {User user = new User();user.setUsername("刘德华");user.setPassword("111");user.setBirthday(new Date());user.setSex("男");user.setAddress("香港");//userDao.insertUser(user);userList.add(user);}userDao.insertUsers(userList);long end = System.currentTimeMillis();System.out.println("一万条数据总耗时:" + (end-start) + "ms" );sqlSession.commit();}
10.7.sql标签
sql元素标签用来定义可重复使用的SQL代码片段,使用时只需要用include元素标签引用即可
- mapper
//复杂条件查询public List<User> findByUser3(User user);
<!-- 定义SQL片段 --><sql id="query_user_where"><if test="username!=null and username != ''">and username=#{username}</if><if test="birthday!=null">and birthday=#{birthday}</if><if test="sex!=null and sex != ''">and sex=#{sex}</if><if test="address!=null and address != ''">and address=#{address}</if></sql><select id="findByUser3" resultType="User">select * from user<where><include refid="query_user_where"></include></where></select>
- 测试
@Testpublic void testFindAll3(){UserDao userDao = sqlSession.getMapper(UserDao.class);User user = new User();user.setAddress("香港");user.setUsername("刘德华");List<User> userList = userDao.findByUser3(user);for(User u : userList){System.out.println(u);}}
11.MyBatis的缓存
创建工程:
11.1缓存介绍
-
为什么使用缓存?
首次访问时,查询数据库,并将数据存储到内存中;再次访问时直接访问缓存,减少IO、硬盘读写次数、提高效率
-
Mybatis中的一级缓存和二级缓存?
-
一级缓存:
它指的是mybatis中的SqlSession对象的缓存。当我们执行完查询之后,查询的结果会同时存在在SqlSession为我们提供的一块区域中。当我们再次查询同样的数据,mybatis会先去SqlSession中查询是否有,有的话直接拿出来使用。当SqlSession对象消失时,Mybatis的一级缓存也就消失了。
-
二级缓存:
它指的是Mybatis中SqlSessionFactory对象的缓存,由同一个SqlSessioFactory对象创建的SqlSession共享其缓存。
-
11.2.一级缓存
11.2.1.mapper
public interface UserDao {//根据id查询用户信息public User findUserById(Integer id);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.by.dao.UserDao"><select id="findUserById" resultType="User" parameterType="int">select * from user where id=#{id}</select>
</mapper>
11.2.2.测试一级缓存
@Testpublic void testFindUserById() throws Exception{SqlSession sqlSession1 = sqlSessionFactory.openSession();UserDao userDao = sqlSession1.getMapper(UserDao.class);User user1 = userDao.findUserById(41);//执行查询System.out.println("第一次查询:" + user1);User user2 = userDao.findUserById(41);//不执行查询System.out.println("第二次查询:" + user2);SqlSession sqlSession2 = sqlSessionFactory.openSession();userDao = sqlSession2.getMapper(UserDao.class);User user3 = userDao.findUserById(41);//执行查询System.out.println("第三次查询:" + user1);}
11.2.3.一级缓存的分析
一级缓存是SqlSession范围的缓存,当调用SqlSession的commit(),close()等方法时,就会清空一级缓存。
-
第一次发起查询用户id为 1 的用户信息,先去找缓存中是否有id为 1 的用户信息,如果没有,从数据库查询用户信息。 得到用户信息,将用户信息存储到一级缓存中。
-
如果sqlSession去执行 commit操作(执行插入、更新、删除),清空 SqlSession 中的一级缓存,这样做的目的为了让缓存中存储的是最新的信息,避免脏读。
-
第二次发起查询用户id为1的用户信息,先去找缓存中是否有id为1的用户信息,缓存中有,直接从缓存中获取用户信息。
11.2.4.测试清空一级缓存
xxxxxxxxxx @Test public void testFindUserById() throws Exception{ UserDao userDao = sqlSession.getMapper(UserDao.class); User user1 = userDao.findUserById(41);//执行查询 System.out.println("第一次查询:" + user1); User user2 = userDao.findUserById(41);//不执行查询 System.out.println("第二次查询:" + user2); sqlSession.commit(); User user3 = userDao.findUserById(41);//执行查询 System.out.println("第三次查询:" + user1); }
11.3.二级缓存
11.3.1.pojo
注意:当我们在使用二级缓存时,所缓存的类一定要实现java.io.Serializable接口,这种就可以使用序列化方式来保存对象。
public class User implements Serializable {private Integer id;private String username;private String password;private Date birthday;private String sex;private String address;//set get... ...
}
11.3.2.开启二级缓存
- 在SqlMapConfig.xml 文件开启二级缓存
<settings><!-- 开启二级缓存的支持 --><setting name="cacheEnabled" value="true"/>
</settings>
- 配置相关的Mapper映射文件
<mapper namespace="com.by.dao.UserDao"><!-- 开启二级缓存的支持 --><cache></cache>
11.3.3.测试二级缓存
@Testpublic void testSecondUserById(){SqlSession sqlSession1 = sqlSessionFactory.openSession();UserDao userDao = sqlSession1.getMapper(UserDao.class);User user1 = userDao.findUserById(41);//执行查询System.out.println("第一次查询:" + user1);sqlSession1.commit();//二级缓存在sqlSession.commit()或者sqlSession.close()之后生效SqlSession sqlSession2 = sqlSessionFactory.openSession();UserDao userDao2 = sqlSession2.getMapper(UserDao.class);User user2 = userDao2.findUserById(41);//不执行查询System.out.println("第二次查询:" + user2);}
11.3.4.二级缓存分析
二级缓存是mapper映射级别的缓存,多个SqlSession去操作同一个Mapper映射的sql语句,多个SqlSession可以共用二级缓存,二级缓存是跨SqlSession的。
二级缓存结构图:
11.3.5.测试清空二级缓存
@Test
public void testSecondUserById(){SqlSession sqlSession1 = sqlSessionFactory.openSession();UserDao userDao = sqlSession1.getMapper(UserDao.class);User user1 = userDao.findUserById(43);//执行查询System.out.println("第一次查询:" + user1);sqlSession1.commit();SqlSession sqlSession3 = sqlSessionFactory.openSession();UserDao userDao3 = sqlSession3.getMapper(UserDao.class);userDao3.deleteUserById(41);sqlSession3.commit();SqlSession sqlSession2 = sqlSessionFactory.openSession();UserDao userDao2 = sqlSession2.getMapper(UserDao.class);User user2 = userDao2.findUserById(43);不执行查询System.out.println("第二次查询:" + user2);sqlSession2.commit();sqlSession2.close();
}
12.MyBatis的注解开发-了解
创建工程:
12.1.注解开发的缺点
MyBatis可以在接口中直接添加MyBatis注解,完成CRUD。
但注解模式属于硬编码到.java文件中,失去了使用配置文件外部修改的优势,可结合需求选用。
12.2.mapper
public interface UserDao {/*** 查询所有用户* @return*/@Select("select * from user")public List<User> findAll();/*** 保存操作* @param user* @return*/@Insert("insert into user(username,sex,birthday,address)values(#{username},“+"#{sex},#{birthday},#{address})")@SelectKey(keyColumn="id",keyProperty="id",resultType=Integer.class,before =false,statement = { "select last_insert_id()" })int saveUser(User user);/*** 更新操作* @param user* @return*/@Update("update user set username=#{username},address=#{address}," +"sex=#{sex},birthday=#{birthday} where id =#{id} ")void updateUser(User user);/*** 删除用户* @param id* @return*/@Delete("delete from user where id = #{id} ")void deleteUser(Integer id);/*** 查询使用聚合函数* @return*/@Select("select count(*) from user ")int findTotal();/*** 根据id查询用户* @return*/@Select("select * from user where id = #{id} ")public User findById(Integer id);/*** 一对多* @return*/@Results(id="resultMap",value= {@Result(id=true,column="id",property="id"),@Result(column="username",property="username"),@Result(column="sex",property="sex"),@Result(column="address",property="address"),@Result(column="birthday",property="birthday"),@Result(column="id",property="accounts",many=@Many(select="com.by.dao.AccountDao.findByuId",fetchType= FetchType.LAZY))})@Select("select * from user")public List<User> findAll2();
}
public interface AccountDao {@Results(id="accountMap",value= {@Result(id=true,column="id",property="id"),@Result(column="uid",property="uid"),@Result(column="money",property="money"),@Result(column="uid",property="user",one=@One(select="com.by.dao.UserDao.findById",fetchType= FetchType.LAZY))})@Select("select * from account")List<Account> findAll();@Select("select * from account where uid = #{uid} ")List<Account> findByuId(Integer id);
}
12.3.pojo
public class User implements Serializable {private Integer id;private String username;private String password;private Date birthday;private String sex;private String address;private List<Account> accounts;//一对多关系映射private List<Account> accounts;// get set toString方法省略
}
public class Account implements Serializable {private Integer id;private Integer uid;private Double money;//一对一关系映射private User user;// get set toString方法省略
}
12.4.测试
@Testpublic void testFindAll() throws Exception{UserDao userDao = sqlSession.getMapper(UserDao.class);List<User> userList = userDao.findAll2();for(User user : userList){System.out.println(user);}}