trim标签可以代替where标签、set标签
//修改
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>
foreach标签的常见使用场景是集合进行遍历
//批量删除
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);
@Test
public 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);
}
@Test
public 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();
}
sql元素标签用来定义可重复使用的SQL代码片段,使用时只需要用include元素标签引用即可
//复杂条件查询
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>
@Test
public 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);
}
}
为什么使用缓存?
首次访问时,查询数据库,并将数据存储到内存中;再次访问时直接访问缓存,减少IO、硬盘读写次数、提高效率
Mybatis中的一级缓存和二级缓存?
public interface UserDao {
//根据id查询用户信息
public User findUserById(Integer id);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//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>
@Test
public 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);
}
一级缓存是SqlSession范围的缓存,当调用SqlSession的commit(),close()等方法时,就会清空一级缓存。
第一次发起查询用户id为 1 的用户信息,先去找缓存中是否有id为 1 的用户信息,如果没有,从数据库查询用户信息。 得到用户信息,将用户信息存储到一级缓存中。
如果sqlSession去执行 commit操作(执行插入、更新、删除),清空 SqlSession 中的一级缓存,这样做的目的为了让缓存中存储的是最新的信息,避免脏读。
第二次发起查询用户id为1的用户信息,先去找缓存中是否有id为1的用户信息,缓存中有,直接从缓存中获取用户信息。
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); }
注意:当我们在使用二级缓存时,所缓存的类一定要实现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... ...
}
<settings>
<!-- 开启二级缓存的支持 -->
<setting name="cacheEnabled" value="true"/>
</settings>
<mapper namespace="com.by.dao.UserDao">
<!-- 开启二级缓存的支持 -->
<cache></cache>
@Test
public 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);
}
二级缓存是mapper映射级别的缓存,多个SqlSession去操作同一个Mapper映射的sql语句,多个SqlSession可以共用二级缓存,二级缓存是跨SqlSession的。
二级缓存结构图:
@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();
}
MyBatis可以在接口中直接添加MyBatis注解,完成CRUD。
但注解模式属于硬编码到.java文件中,失去了使用配置文件外部修改的优势,可结合需求选用。
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);
}
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方法省略
}
@Test
public void testFindAll() throws Exception{
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.findAll2();
for(User user : userList){
System.out.println(user);
}
}