使用注解开发
删除 UserMapper.xml
UserMapper
package com.hou.dao;
import com.hou.pojo.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
}
核心配置 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"/>
<!--可以给实体类起别名-->
<typeAliases>
<typeAlias type="com.hou.pojo.User" alias="User"></typeAlias>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--绑定接口-->
<mappers>
<mapper class="com.hou.dao.UserMapper"></mapper>
</mappers>
</configuration>
本质:反射机制
底层:动态代理!
Mybatis详细执行流程:
Resource获取全局配置文件
实例化SqlsessionFactoryBuilder
解析配置文件流XMLCondigBuilder
Configration所有的配置信息
SqlSessionFactory实例化
trasactional事务管理
创建executor执行器
创建SqlSession
实现CRUD
查看是否执行成功
提交事务
关闭
注解CRUD
package com.hou.dao;
import com.hou.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
//方法存在多个参数,所有的参数必须加@Param
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
@Insert("insert into user (id, name, pwd) values" +
"(#{id},#{name},#{password})")
int addUser(User user);
@Update("update user set name=#{name}, pwd=#{password} " +
"where id=#{id}")
int updateUser(User user);
@Delete("delete from user where id=#{id}")
int deleteUser(@Param("id") int id);
}
MybatisUtile
package com.hou.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
//sqlSessionFactory --> sqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
Test
package com.hou.dao;
import com.hou.pojo.User;
import com.hou.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
// 获得sqlsession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
// 1.执行 getmapper
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
List<User> userList = userDao.getUsers();
for (User user : userList) {
System.out.println(user);
}
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭
sqlSession.close();
}
}
@Test
public void getuserById(){
// 获得sqlsession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
// 1.执行 getmapper
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
User user = userDao.getUserById(1);
System.out.println(user);
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭
sqlSession.close();
}
}
@Test
public void addUser(){
// 获得sqlsession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
// 1.执行 getmapper
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
userDao.addUser(new User(6, "kun","123"));
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭
sqlSession.close();
}
}
@Test
public void updateUser(){
// 获得sqlsession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
// 1.执行 getmapper
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
userDao.updateUser(new User(6, "fang","123"));
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭
sqlSession.close();
}
}
@Test
public void deleteUser(){
// 获得sqlsession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
// 1.执行 getmapper
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
userDao.deleteUser(6);
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭
sqlSession.close();
}
}
}
8. Lombok
在IDEA中安装lombok插件
配置
<dependencies>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@Data: 无参构造,get,set,toString,hashCode
在实体类上加注解
package com.hou.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String password;
}
9. 多对一处理
多个学生关联一个老师(多对一)
集合(一对多)
1. 建表
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO teacher (`id`, `name`) VALUES (1, 'hou');
CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO student (`id`, `name`, `tid`) VALUES (1, 'xiao1', 1);
INSERT INTO student (`id`, `name`, `tid`) VALUES (2, 'xiao2', 1);
INSERT INTO student (`id`, `name`, `tid`) VALUES (3, 'xiao3', 1);
INSERT INTO student (`id`, `name`, `tid`) VALUES (4, 'xiao4', 1);
INSERT INTO student (`id`, `name`, `tid`) VALUES (5, 'xiao5', 1);
新建实体类
package com.hou.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private Teacher teacher;
}
package com.hou.pojo;
import lombok.Data;
@Data
public class Teacher {
private int id;
private String name;
}
建立Mapper接口
建立Mapper.xml
测试是否能够成功
2. 按照查询嵌套处理
StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hou.dao.StudentMapper">
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<resultMap id="StudentTeacher" type="com.hou.pojo.Student">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<!--对象使用assiociation-->
<!--集合用collection-->
<association property="teacher" column="tid"
javaType="com.hou.pojo.Teacher"
select="getTeacher"></association>
</resultMap>
<select id="getTeacher" resultType="com.hou.pojo.Teacher">
select * from teacher where id = #{id};
</select>
</mapper>
3. 按照结果嵌套处理
select s.id sid,s.name sname,t.name tname
from student s,teacher t where s.tid=t.id;
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from student s,teacher t where s.tid=t.id;
</select>
<resultMap id="StudentTeacher2" type="com.hou.pojo.Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<association property="teacher" javaType="com.hou.pojo.Teacher">
<result property="name" column="tname"></result>
</association>
</resultMap>
property 映射到列结果的字段或属性。
column 数据库中的列名,或者是列的别名。
10. 一对多
一个老师拥有多个学生
对于老师而言就是一对多
1.环境搭建
实体类
package com.hou.pojo;
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
private List<Student> studentList;
}
package com.hou.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int tid;
}
- 按照结果查询
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname, t.name tname, t.id tid
from student s, teacher t
where s.tid = t.id and t.id = #{id};
</select>
<resultMap id="TeacherStudent" type="com.hou.pojo.Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<!--集合中的泛型信息,我们用oftype获取-->
<collection property="studentList" ofType="com.hou.pojo.Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
</collection>
</resultMap>
3. 按照查询嵌套处理
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id = #{id}
</select>
<resultMap id="TeacherStudent2" type="com.hou.pojo.Teacher">
<collection property="studentList" column="id" javaType="ArrayList"
ofType="com.hou.pojo.Student"
select="getStudentByTeacherId"></collection>
</resultMap>
<select id="getStudentByTeacherId" resultType="com.hou.pojo.Student">
select * from mybatis.student where tid = #{id}
</select>
小结
关联 - association 多对一
集合 - collection 一对多
javaType & ofType
JavaType用来指定实体中属性类型
ofType映射到list中的类型,泛型中的约束类型
注意点:
保证sql可读性,尽量保证通俗易懂
注意字段问题
如果问题不好排查错误,使用日志
11. 动态sql
动态sql:根据不同的条件生成不同的SQL语句
- 搭建环境
create table `blog`(
`id` varchar(50) not null comment '博客id',
`title` varchar(100) not null comment '博客标题',
`author` varchar(30) not null comment '博客作者',
`create_time` datetime not null comment '创建时间',
`views` int(30) not null comment '浏览量'
)ENGINE=InnoDB DEFAULT CHARSET=utf8
实体类
package com.hou.pojo;
import lombok.Data;
import java.util.Date;
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
核心配置
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hou.mapper.BlogMapper">
<insert id="addBlog" parameterType="Blog">
insert into mybatis.blog (id, title, author, create_time, views) values
(#{id}, #{title}, #{author}, #{create_time}, #{views});
</insert>
</mapper>
新建随机生成ID包
package com.hou.utils;
import org.junit.Test;
import java.util.UUID;
@SuppressWarnings("all")
public class IDUtiles {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
@Test
public void test(){
System.out.println(getId());
}
}
测试类:添加数据
import com.hou.mapper.BlogMapper;
import com.hou.pojo.Blog;
import com.hou.utils.IDUtiles;
import com.hou.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
public class MyTest {
@Test
public void addBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtiles.getId());
blog.setAuthor("houdongun");
blog.setCreateTime(new Date());
blog.setViews(999);
blog.setTitle("first");
blogMapper.addBlog(blog);
blog.setId(IDUtiles.getId());
blog.setTitle("second");
blogMapper.addBlog(blog);
blog.setId(IDUtiles.getId());
blog.setTitle("third");
blogMapper.addBlog(blog);
blog.setId(IDUtiles.getId());
blog.setTitle("forth");
blogMapper.addBlog(blog);
sqlSession.close();
}
}
- if
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from mybatis.blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != author">
and author = #{author}
</if>
</select>
test
@Test
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
// map.put("title", "second");
map.put("author", "houdongun");
List<Blog> list = blogMapper.queryBlogIF(map);
for (Blog blog : list) {
System.out.println(blog);
}
sqlSession.close();
}
3. choose、when、otherwise
<select id="queryBlogchoose" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
4. trim、where、set
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
</update>
trim 可以自定义
SQL片段
有些时候我们有一些公共部分
使用sql便签抽取公共部分
在使用的地方使用include标签
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
注意:
最好基于单表
sql里不要存在where标签
5. for-each
<!--ids是传的,#{id}是遍历的-->
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and ("
close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
test
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(3);
map.put("ids",ids);
List<Blog> list = blogMapper.queryBlogForeach(map);
for (Blog blog : list) {
System.out.println(blog);
}
sqlSession.close();
}
- 缓存(了解)
- 一级缓存
开启日志
测试一个session中查询两次相同记录。
缓存失效:
映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
查询不同的mapper.xml
手动清除缓存
一级缓存默认开启,只在一次sqlseesion中有效
- 二级缓存
开启全局缓存
<setting name="cacheEnabled" value="true"/>
在当前mapper.xml中使用二级缓存
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
test
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession1 = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.queryUserByid(1);
System.out.println(user);
sqlSession.close();
UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
User user1 = userMapper1.queryUserByid(1);
System.out.println(user1);
System.out.println(user==user1);
sqlSession1.close();
}
只用cache时加序列化
**实体类**
package com.hou.pojo;
import lombok.Data;
import java.io.Serializable;
@Data
public class User implements Serializable {
private int id;
private String name;
private String pwd;
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
}
小结:
只有开启了二级缓存,在Mapper下有效
所有数据都会先放在一级缓存
只有当回话提交,或者关闭的时候,才会提交到二级缓存
3. 自定义缓存-ehcache
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.0</version>
</dependency>
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--
diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
user.home – 用户主目录
user.dir – 用户当前工作目录
java.io.tmpdir – 默认临时文件路径
-->
<diskStore path="java.io.tmpdir/Tmp_EhCache"/>
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
-->
<!--
name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>