Mybatis
一、简介
概念
- 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(普通老式 Java 对象)为数据库中的记录。
获取Mybatis:
- maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
- 中文文档 https://mybatis.org/mybatis-3/zh/index.html
持久化
就是将程序的数据在持久状态和瞬时状态转化的过程
因为有很多数据会在某种情况下会消失,所以要保持持久化 例如内存(断电及失)
持久层
完成持久化工作的代码块 层界线十分明显
优点
- 简单易学
- 灵活
- sql和代码实现分离,提高了可维护性
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组件维护
- 提供xml标签,支持编写动态SQL
作用域+生命周期
作用域和生命周期类别是至关重要的,错误的使用会导致非常严重的并发问题
-
SqlSessionFactoryBuilder
- 这个类用来创建SqlSessionFactory。
- 一旦创建了SqlSessionFactory,就不再需要它了。
- 作用域是方法作用域(也就是局部方法变量)。
-
SqlSessionFactory
- SqlSessionFactory 其实就是数据库连接池
- 使用单例模式或者静态单例模式,在运行期间一直存在
- 最佳作用域是应用作用域
-
SqlSession
- 其实就是连接到连接池的一个请求
- 作用域是请求或方法作用域。
- 用完以后,就关闭它,不然有可能造成资源被占用
二、创建Mybatis程序
1.搭建环境
- 创建mysql数据库 表格
- 配置maven 下载apache-maven-3.6.3-bin文件,然后配置到idea中
- 新建maven项目 将src文件删掉
- 配置xml文件 添加junit,mysql,mybatis依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
2.创建模块
创建一个maven模块 其中xml文件自动继承了上一个project的xml了,不需要再导包了
mybatis中文文档:https://mybatis.org/mybatis-3/zh/getting-started.html
-
编写mybatis工具类
创建一个MybatisUtils类在src/main/java/com.wjh.utils下 代码都可以在文档中获取
创建Factory对象 (基于MyBatis的应用都是以一个SqlSessionFactory的实例为核心的)
SqlSessionFactory创建后,可以从中获得 SqlSession。 (SqlSession提供了在数据库执行 SQL 命令所需的所有方法)
public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static{ String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
-
db.propertis
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8 username=root password=123456
-
编写模块中xml核心配置文件 (创建mybatis-config.xml文件 放置于src/main/resources下) 主要针对mysql数据库
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="db.properties"/> <typeAliases> <package name="com.wjh.pojo"/> </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 resource="com/wjh/dao/UserMapper.xml"/> </mappers> </configuration>
-
实体类 (User.java)
-
Mapper接口类
public interface UserMapper { List<User> getUsers(); }
-
Mappr配置文件 【用来实现sql语句】
- namespace 链接Mapper接口类
- id Dao接口类中方法名
- resultType sql语句的返回值类型 (如果是自定义的类,那么写出类的路径)
- parameterType 传入的参数类型
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.wjh.dao.UserMapper"> <select id="selectUser" resultType="user"> select * from user </select> </mapper>
-
最后!!!注册mappr.xml文件到mybatis核心配置文件中
<mappers>
<mapper resource="com/wjh/dao/UserMapper.xml"/>
</mappers>
3.测试
使用junit进行测试
测试类要写到src/test/java文件夹下 并且最好test下的包名与上面main/java中的包名保持一致
@Test
public void test(){
//获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//创建dao对象,用来调用方法
UserDao mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
for (User u:users
) {
System.out.println(u.getId()+"---"+u.getName()+"---"+u.getPassword());
}
//关闭SQLSession
sqlSession.close();
}
maven约定大于配置,可能会遇到写的配置文件无法被到处或者生效的问题,在pom.xml中添加
如果没有配置,那么会提示错误: java.lang.ExceptionInInitializerError
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
三、CURD
注意注意:增删改都需要提交事务
sqlSession.commit();
才可以发挥作用,不然执行代码也是无用的
步骤:
-
写Mapper接口类 写方法
-
写Mapper.xml
parameterType 表示输入数据类型 当要传入数据 表示为#{数据名}
<select id="getUserById" resultType="com.wjh.pojo.User" parameterType="int"> select * from mybatis.user where id=#{id} </select>
-
写测试类
- 得到sqlSession
- 得到Mapper
- 调用方法
- 关闭sqlSession
增
-
Mapper类
int addUser(User user);
-
Mapper.xml
<insert id="addUser" parameterType="com.wjh.pojo.User"> insert into mybatis.user (id,name,password) values(#{id},#{name},#{password}) </insert>
-
测试类
SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.addUser(new User(4,"哈哈哈哈","121212")); sqlSession.commit(); //提交事务 sqlSession.close();
删
-
Mapper类
int deleteUser(int id);
-
Mapper.xml
<delete id="deleteUser" parameterType="int"> delete from mybatis.user where id=#{id} </delete>
改
-
Mapper类
int updateUser(User user);
-
Mapper.xml
<update id="updateUser" parameterType="com.wjh.pojo.User"> update mybatis.user set name=#{name},password=#{password} where id=#{id} </update>
查
-
Mapper类
//查询所有数据 List<User> getUsers(); //根据id查询数据 User getUserById(int id);
-
Mapper.xml
<select id="getUsers" resultType="com.wjh.pojo.User"> select * from mybatis.user </select> <select id="getUserById" resultType="com.wjh.pojo.User" parameterType="int"> select * from mybatis.user where id=#{id} </select>
Map CURD
如果实体类,数据库表,字段或者参数过多,可以考虑使用Map
使用实体类的话,每次CURD都要创建一个对象,很麻烦 Map不需要,只需要创建需要的参数即可
-
Map增加数据
int addUserByMap(Map<String,Object> map);
<insert id="addUserByMap" parameterType="Map"> insert into user (id,name,password) values(#{id},#{name},#{pwd}) </insert>
Map<String,Object> map = new HashMap<String, Object>(); map.put("id",5); mapper.addUserByMap(map);
-
map查询数据 可以通过属性得到数据
<select id="getUserByMId" parameterType="Map" resultType="com.wjh.pojo.User"> select * from user where id=#{userId} and name=#{name} </select>
UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map<String,Object> map = new HashMap<String, Object>(); map.put("userId",4); map.put("name","嘿嘿嘿"); User u = mapper.getUserByMId(map);
模糊查询
通过传入参数的样式来得到数据
- 在测试类中写出参数的样式
//Like传参
List<User> getUserLike(String value);
<select id="getUserLike" parameterType="String" resultType="com.wjh.pojo.User">
select * from user where name like #{value}
</select>
List<User> list = new ArrayList<User>();
list = mapper.getUserLike("%张%");
for (User l:list
) {
System.out.println(l);
}
- 在xml中写出样式
<select id="getUserLike" parameterType="String" resultType="com.wjh.pojo.User">
select * from user where name like "%"#{value}"%"
</select>
四、配置文件解析
核心配置文件
配置文件包含了会深深影响 MyBatis 行为的设置和属性信息
configuration(配置)
- [properties(属性)]
- [settings(设置)]
- [typeAliases(类型别名)]
- [typeHandlers(类型处理器)]
- [objectFactory(对象工厂)]
- [plugins(插件)]
- environments(环境配置)
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- [databaseIdProvider(数据库厂商标识)]
- [mappers(映射器)]
环境配置environments
Mybatis可以适应多种环境 但最后SqlSessionFactory只能选择一种环境
Mybatis默认的事务管理器是JDBC 连接池:POOLED
属性properties
-
引入配置文件
db.properties
-
也可以在properties中直接写属性及内容
-
优先使用外部的配置文件 当外部和内部有相同的属性的时候
引入外部配置文件
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
xml
<properties resource="db.properties"/>
...
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
内部配置
xml
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="123456"/>
</properties>
...
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
别名typeAliases
类型别名可为 Java 类型设置一个缩写名字
意在降低冗余的全限定类名书写。
- 通过别名类型取别名
xml
<typeAliases>
<typeAlias type="com.wjh.pojo.User" alias="User"/>
</typeAliases>
Mapper.xml
<select id="getUsers" resultType="User">
select * from mybatis.user
</select>
-
通过包取别名
-
当类没有写注解的时候,默认别名为类的小写
<typeAliases> <package name="com.wjh.pojo"/> </typeAliases>
<select id="getUsers" resultType="user"> select * from mybatis.user </select>
-
当写了注解,那么别名就是注解的内容
@Alias("hello") public class User {}
<select id="getUsers" resultType="hello"> select * from mybatis.user </select>
-
设置settings
改变 MyBatis 的运行时行为
设置 | 作用 |
---|---|
cacheEnabled | 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 |
lazyLoadingEnabled | 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 |
mapUnderscoreToCamelCase | 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。 |
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
映射器mappers
MapperRegistry:注册绑定Mapper文件
方式一:通过调取资源文件地址 推荐使用这个方法!
<mappers>
<mapper resource="com/wjh/dao/UserMapper.xml"/>
</mappers>
方式二:通过调用反射类 不推荐!
<mapper class="com.wjh.dao.UserMapper"/>
方式三:通过调用包名 也不推荐!
<package name="com.wjh.dao"/>
方法二、三需要注意:
- Mapper类和Mapper.xml名字必须保持一致
- Mapper类和Mapper.xml必须在同一个包下
五、结果集映射
问题
当实体类中的属性名和数据库表格的字段名不相同时,就需要设置结果集映射
public class User {
private int id;
private String name;
private String pwd;
}
但是数据库表字段为 id name password
当查询数据库信息的时候,就查不到password的信息,会显示为null
-
起别名
可以为字段名起别名为实体类属性名 也可以得到数据
<select id="getUsers" resultType="user"> select id,name,password as pwd from mybatis.user </select>
resultMap
Mapper.xml
<resultMap id="userResultMap" type="user">
<result property="pwd" column="password"/>
</resultMap>
<select id="getUsers" resultMap="userResultMap">
select * from mybatis.user
</select>
六、日志
当数据库操作出现异常,使用日志,可以看到异常情况
通过在setting里通过logImpl设置 ,指定所用日志的具体实现
- LOG4J 【掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING 【掌握】
- NO_LOGGING
1.标准的日志工厂实现
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
2.LOG4J
概念:
- 可以控制日志信息输送到控制台、文件、GUI组件
- 可以控制日志的输出格式
- 可以定义每一条日志信息的级别
- 通过配置文件进行配置,不需要修改应用的代码
测试log4j
-
导包
-
配置pom.xml
<dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
-
创建log4j.properties
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码 log4j.rootLogger=DEBUG,console,file #控制台输出的相关设置 log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=【%c】-%m%n #文件输出的相关设置 log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/kuang.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=【%p】【%d{yy-MM-dd}】【%c】%m%n #日志输出级别 log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
-
mybatis-config.xml
<settings> <setting name="logImpl" value="LOG4J"/> </settings>
-
测试log4j
static Logger logger = Logger.getLogger(UserMapperTest.class); @Test public void testLog4j(){ logger.info("info:进入了testLog4j"); logger.debug("debug:进入了testLoh4j"); logger.error("error:进入了testLog4j"); } 结果: [com.wjh.dao.UserMapperTest]-info:进入了testLog4j [com.wjh.dao.UserMapperTest]-debug:进入了testLoh4j [com.wjh.dao.UserMapperTest]-error:进入了testLog4j
七、分页
- 减少数据的处理量
- 提高查询效率
SQL使用LIMIT分页
select * from user limit startIndex,pageSize
select * from user limit 0,3 //获取前三个数据
通过Mybatis实现分页
-
Mapper.java
List<User> getUsersByLimit(Map<String,Object> map);
-
Mapper.xml
<select id="getUsersByLimit" resultMap="userResultMap" parameterType="map"> select * from user limit #{start},#{end} </select>
-
测试
Map<String,Object> map = new HashMap<String, Object>(); map.put("start",0); map.put("end",3); List<User> list = mapper.getUsersByLimit(map); for (User user : list) { System.out.println(user); } 结果: User{id=1, name='张三', pwd='123456'} User{id=2, name='李四', pwd='666666'} User{id=4, name='嘿嘿嘿', pwd='111111'}
Mybatis分页插件PageHelper
八、注解
面向接口编程
就是定义和实现的分离
自动提交事务
MybatisUtil.java
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true); //设置为true表示自动提交事务
}
CURD
查询数据
-
Mapper.java
@Select("select * from user") List<User> getUsers();
-
注册到核心配置文件
不需要Mapper.xml文件了,也不需要再注册这个文件 当然,也可以注册xml文件
不过不可以同时注册xml文件和java文件!!!
<mappers> <mapper class="com.wjh.dao.UserMapper"/> </mappers>
-
测试
List<User> list = mapper.getUsers(); for (User user : list) { System.out.println(user); }
增加数据
-
Mapper.java
@Insert("insert into user (id,name,password) values (#{id},#{name},#{password})") int addUser(User user);
删除数据
-
Mapper.java
@Delete("delete from user where id=#{uid}") int deleteUser(@Param("uid") int id);
修改数据
-
Mapper.java
@Update("update user set name=#{name},password=#{password} where id=#{id}") int updateUser(User user);
Param()注解
- 使用
Param()
注解后,调用的时候就要写成注解设定的数据了 - 当数据类型为基本类型的数据的时候,就要加上它
- 引用类型不需要加它
- 当数据只有一个,可以不加,但是最好加上
#{} ${}
- ${} 可以拼接,有SQL注入的风险
- 尽量使用#{} 可以防止SQL注入
- SQL 注入:就是在用户输入的字符串中加入 SQL 语句,那么这些注入进去的 SQL 语句就会被数据库服务器误认为是正常的 SQL 语句而运行,攻击者就可以执行计划外的命令或访问未被授权的数据。
九、LomBok
LomBok是一个java库,它可以自动插入到编辑器和构建工具中,增强java的性能。不需要再写getter、setter或equals方法,只要设置了注解就可以调用
-
下载LomBok插件
-
添加配置
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> <scope>provided</scope> </dependency>
-
添加注解
@Data //get set @NoArgsConstructor //无参构造 @AllArgsConstructor //有参构造
十、多对一查询
多个student对应一个teacher
-
创表
create table teacher( id int(10) PRIMARY KEY NOT NULL, name varchar(30) DEFAULT NULL )ENGINE=INNODB DEFAULT CHARSET=utf8
CREATE table student ( id int(10) PRIMARY KEY NOT NULL, name VARCHAR(30) DEFAULT NULL, tid INT(10) DEFAULT NULL, CONSTRAINT stfid FOREIGN KEY(tid) REFERENCES teacher(id) )ENGINE=INNODB DEFAULT CHARSET=utf8
查询Student并且查出Student对应的Teacher信息
-
实体类
public class Student { private int id; private String name; private Teacher teacher; //因为tid是teacher的信息,所以定义为teacher } public class Teacher { private int id; private String name; }
查询
-
SQL连表查询
select s.id,s.name,t.name from student s,teacher t where s.tid=t.id
-
Mybatis查询
通过结果集映射将两个实体类联系起来,达到查找Student和Teacher 的目的
在结果集映射中,对于复杂的数据类型,要使用association表示对象 collection表示集合
-
按照查询嵌套处理
-
相当于SQL的子查询
-
先写出查询Student的select 通过调用resultMap来查询teacher,进而将teacher显示在student中
-
之后写resultMap,用在Student的查询上,表示Student查出的结果为id,name,teacher 而teacher就是tid,通过tid在teacher查询到teacher的信息
<select id="getStudentAndT" resultMap="StudentTeacher"> select * from student </select> <resultMap id="StudentTeacher" type="student"> <result property="id" column="id"/> <result property="name" column="name"/> <association property="teacher" column="tid" select="getTeacher" javaType="Teacher"/> </resultMap> <select id="getTeacher" resultType="Teacher"> select * from teacher where id=#{id} </select> Student(id=1, name=张三, teacher=Teacher(id=1, name=老师)) Student(id=2, name=李四, teacher=Teacher(id=1, name=老师)) Student(id=3, name=王五, teacher=Teacher(id=1, name=老师)) Student(id=4, name=小红, teacher=Teacher(id=1, name=老师)) Student(id=5, name=小李, teacher=Teacher(id=1, name=老师))
-
-
按照结果嵌套处理
- 相当于SQL的联表查询
- 先用select写出查询语句,之后在resultMap中将每一行都表示出来 association表示teacher,在里面写出teacher的查询,进而查询所有数据
<select id="getSTByResult" resultMap="ST"> select s.id sid,s.name sname,t.id tid,t.name tname from student s,teacher t where s.tid=t.id </select> <resultMap id="ST" type="student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> </association> </resultMap>
-
十一、一对多查询
一个teacher对应多个student
获取指定老师的信息以及老师对应的学生信息
注意:现在一对多查询,查出来的是一个集合,所以resultMap中的students不应该用association了,应该用collection
-
实体类
public class Teacher { private int id; private String name; private List<Student> students; } public class Student { private int id; private String name; private Teacher teacher; }
查询
可以查出每个老师包含的学生信息
-
联表查询
<select id="getTS" resultMap="TS"> select t.id tid,t.name tname,s.id sid,s.name sname from teacher t,student s where t.id=s.tid </select> <resultMap id="TS" type="teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <collection property="students" ofType="student"> <result property="id" column="sid"/> <result property="name" column="sname"/> </collection> </resultMap> Teacher(id=1, name=1号老师, students=[Student(id=1, name=张三, tid=0), Student(id=3, name=王五, tid=0), Student(id=5, name=小李, tid=0)]) Teacher(id=2, name=2号老师, students=[Student(id=2, name=李四, tid=0), Student(id=4, name=小红, tid=0)])
-
子查询
<select id="getTS2" resultMap="TS2"> select * from teacher </select> <resultMap id="TS2" type="teacher"> <result property="id" column="id"/> <result property="name" column="name"/> <collection property="students" select="getStudent" ofType="student" column="id"/> </resultMap> <select id="getStudent" resultType="student"> select * from student where tid=#{id} </select>
-
总结
多对一:用关联association 指定实体类中属性的类型用javaType
一对多:用集合collection 指定映射到List或者集合中的pojo类型,泛型中的约束类型用ofType
十二、动态SQL
就是根据不同的条件生成不同的SQL语句
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
环境搭建
- 创建表格
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4v03tarf-1665371696264)(C:\Users\WangJh\AppData\Roaming\Typora\typora-user-images\image-20221001213607344.png)]
-
创建实体类
@Data public class Blog { private String id; private String title; private String author; private Date createTime; //之后在核心配置文件中添加配置settings 表示驼峰映射 private int views; }
-
配置驼峰命名
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings>
-
创建IDUtils工具类
public class IDUtils { public static String getId(){ return UUID.randomUUID().toString().replaceAll("-",""); } }
-
BlogMapper.xml
<insert id="addBlogs" parameterType="blog"> insert into blog (id,title,author,create_time,views) values (#{id},#{title},#{author},#{createTime},#{views}) </insert>
注意:配置了驼峰命名后,在写sql的时候,
insert into blog (id,title,author,create_time,views) values
中,一定要写成表格的字段名,不可以写成实体类的属性名!不然会报错org.apache.ibatis.exceptions.PersistenceException
IF
设置查询的条件,符合if中的条件 进行查询
-
BlogMapper.java
用Map传参数
List<Blog> queryBlog(Map map);
-
BlogMapper.xml
设置当views和author不为空的条件下,查询数据
<select id="queryBlog" parameterType="map" resultType="Blog"> select * from blog where 1=1 <if test="views!=null"> and views=#{views} </if> <if test="author!=null"> and author=#{author} </if> </select>
choose (when, otherwise)
相当于Java中的SwitchCase语句
<select id="queryBlogsByChoose" resultType="blog" parameterType="map">
select * from blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=null">
author=#{author}
</when>
<otherwise>
views=#{views}
</otherwise>
</choose>
</where>
</select>
trim (where, set)
-
where
-
where元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
-
查询
<select id="queryBlog" parameterType="map" resultType="Blog"> select * from blog <where> <if test="views!=null"> views=#{views} </if> <if test="author!=null"> and author=#{author} </if> </where> </select>
-
-
set
-
set用在更新语句中 会动态地在行首插入 SET 关键字,并会删掉额外的逗号
-
使用
<update id="updateBlog" parameterType="map"> update blog <set> <if test="title!=null"> title=#{title}, </if> <if test="author!=null"> author=#{author} </if> where id=#{id} </set> </update>
-
SQL片段
SQL片段其实就是将SQL语句拆开,拿出一部分,方便复用
-
片段 sql id命名
<sql id="if"> <if test="views!=null"> views=#{views} </if> <if test="author!=null"> and author=#{author} </if> </sql>
-
调用片段 include refid调用
<select id="queryBlog" parameterType="map" resultType="Blog"> select * from blog <where> <include refid="if"/> </where> </select>
foreach
当要查询多个数据,在SQL中会设置多个条件,用or或者and来分割,那么可以使用foreach来实现
-
表达式:
- collection:要传入的集合
- open:以…为开头
- close:以…为结尾
- item:集合中的数据
- separator:用…分割集合中的数据
<select id="getBlogByForeach" parameterType="map" resultType="blog"> select * from blog <where> <foreach collection="list" open="and (" close=")" index="index" item="item" separator=","> #{item} </foreach> </where> </select>
-
sql语句
select * from blog where 1=1 and (id=1 or id=2)
-
foreach
<select id="getBlogByForeach" parameterType="map" resultType="blog"> select * from blog <where> <foreach collection="list" open="and (" close=")" item="id" separator="or"> id=#{id} </foreach> </where> </select>
Map<String,Object> map = new HashMap<String, Object>(); List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); map.put("list",list); List<Blog> blogs = mapper.getBlogByForeach(map);
十三、缓存
简介
- 概念
- 缓存就是存在内存中的临时数据
- 将用户经常查询的数据放在缓存中,用户查询数据就不用从磁盘上查询,而是直接从缓存中查询,提高查询效率,解决高并发系统的性能问题
- 为什么使用缓存
- 减少和数据库的交互次数,减少系统开销,提高系统效率
- 什么数据使用缓存
- 经常查询而且不经常改变的数据
Mybatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存,缓存可以极大的提升查询效率。
- MyBatis系统中默认定义了两级缓存: 一级缓存和二级缓存
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)。
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高扩展性,MyBatis定义了缓存接口Cache。可以通过实现Cache接口来自定义二级缓存
- 清除策略
- LRU:移除最长时间不被使用的对象 【默认】
- FIFO:先进先出 按照对象进入缓存的顺序移除
一级缓存
-
默认存在,每次执行它都存在
-
缓存失效条件
-
对数据进行增删改的操作,会刷新缓存
-
查询不同数据
-
手动清除缓存
sqlSession.clearCache();
-
二级缓存
- 二级缓存也称为全局缓存
- 是基于namespace级别的缓存,一个命名空间对应一个二级缓存
- 工作机制
- 当一个会话查询数据的时候,会存放在一级缓存中
- 如果会话关闭,一级缓存就会消失,使用二级缓存的话,就可以将一级缓存的数据保存到二级缓存中
- 不同mapper查出的数据会放在自己对应的缓存中
- 注意:只有当会话关闭的时候,一级缓存的数据才会保存到二级缓存中
步骤:
-
开启全局缓存(默认已经开启)
<setting name="cacheEnabled" value="true"/>
-
对要使用的mapper进行设置
<cache/>
还可以自定义缓存的参数,选择缓存策略,缓存时间等等
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/> 这个缓存表示:创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的
查询顺序
先看二级缓存,再看一级缓存,最后看数据库
一般使用Redis数据库来做缓存
- 概念
- 缓存就是存在内存中的临时数据
- 将用户经常查询的数据放在缓存中,用户查询数据就不用从磁盘上查询,而是直接从缓存中查询,提高查询效率,解决高并发系统的性能问题
- 为什么使用缓存
- 减少和数据库的交互次数,减少系统开销,提高系统效率
- 什么数据使用缓存
- 经常查询而且不经常改变的数据
Mybatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存,缓存可以极大的提升查询效率。
- MyBatis系统中默认定义了两级缓存: 一级缓存和二级缓存
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)。
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高扩展性,MyBatis定义了缓存接口Cache。可以通过实现Cache接口来自定义二级缓存
- 清除策略
- LRU:移除最长时间不被使用的对象 【默认】
- FIFO:先进先出 按照对象进入缓存的顺序移除
一级缓存
-
默认存在,每次执行它都存在
-
缓存失效条件
-
对数据进行增删改的操作,会刷新缓存
-
查询不同数据
-
手动清除缓存
sqlSession.clearCache();
-
二级缓存
- 二级缓存也称为全局缓存
- 是基于namespace级别的缓存,一个命名空间对应一个二级缓存
- 工作机制
- 当一个会话查询数据的时候,会存放在一级缓存中
- 如果会话关闭,一级缓存就会消失,使用二级缓存的话,就可以将一级缓存的数据保存到二级缓存中
- 不同mapper查出的数据会放在自己对应的缓存中
- 注意:只有当会话关闭的时候,一级缓存的数据才会保存到二级缓存中
步骤:
-
开启全局缓存(默认已经开启)
<setting name="cacheEnabled" value="true"/>
-
对要使用的mapper进行设置
<cache/>
还可以自定义缓存的参数,选择缓存策略,缓存时间等等
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/> 这个缓存表示:创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的
查询顺序
先看二级缓存,再看一级缓存,最后看数据库
一般使用Redis数据库来做缓存