目录
1. mybatis的介绍
MyBatis 是一款优秀的持久层Dao框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Java实体类)映射成数据库中的记录.
2. 为什么使用mybatis框架
可以简化jdbc的操作以及占位符赋值以及查询结果集的封装
3. 如何使用mybatis
(1)引入mybatis和mysql的jar包
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
(2)创建mybatis的配置文件
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!--数据源的配置:name的值固定 value的值根据客自己修改-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis? serverTimezone=Asia/Shanghai" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
(3)创建数据库和表
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`realname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
PRIMARY KEY (`userid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES (1, 'admin', '管理员');
INSERT INTO `tb_user` VALUES (2, 'bjt', '白敬亭');
INSERT INTO `tb_user` VALUES (3, 'wsl', '汪苏泷');
INSERT INTO `tb_user` VALUES (4, 'lyn', '刘宇宁');
(4)创建实体类
public class User {
private int userid;
private String username;
private String realname;
}
(5)创建mybatis和数据库的映射文件
作用: 映射实体和表之间的映射关系
<?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">
<!--namespace:命名空间
可以随便起名,但是后期我们要求命名空间的值必须和所对应的dao相同
-->
<mapper namespace="qy151.user">
<!--查询 根据id查询用户信息
select标签用于查询的标签
id:标签的唯一标识
resultType: 定义返回的类型 把sql查询的结果封装到哪个实体类钟
#{id}===表示占位符等价于? 这是mybatis框架的语法
-->
<select id="findById" resultType="com.abc.entity.User">
select * from tb_user where userid=#{id}
</select>
</mapper>
把映射文件注册到配置文件上mybatis.xml上
<!--注册映射文件-->
<mappers>
<!--resource:引用资源文中的映射文件 url:网络上的映射文件-->
<mapper resource="mapper/UserMapper.xml" />
</mappers>
(6)测试mybatis
public class Test01 {
public static void main(String[] args) throws Exception {
//1.读取mybatis配置文件的内容----未来不需要写tomcat 解析配置文件
Reader reader = Resources.getResourceAsReader("mybatis.xml");
//2. 获取SqlSessionFactory对象
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
//3. 获取SqlSession对象----封装了对数据库操作的各种方法
SqlSession session=factory.openSession();
//调用查询一个结果的接口
//String statement, 命名空间+id----指向sql标签
// Object parameter 需要实参
User user = session.selectOne("qy151.user.findById", 2);
System.out.println(user);
//4.关闭
session.commit();
session.close();
}
}
4. lombok插件
可以生成实体类的get和set方法 而且生成构造方法重写toString方法
(1) idea安装lombok插件
(2)工程中引入lombok依赖
<!--lombok的依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
(3)在实体类上添加lombok注解
@Data //set和get方法以及toString方法
@NoArgsConstructor //无参构造方法
@AllArgsConstructor //所有参数的构造方法
public class User {
private int userid;
private String username;
private String realname;
}
5. 使用mybatis完成crud
<?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">
<!--namespace:命名空间
可以随便起名,但是后期我们要求命名空间的值必须和所对应的dao相同
-->
<mapper namespace="qy151.user">
<!--查询 根据id查询用户信息
select标签用于查询的标签
id:标签的唯一标识
resultType: 定义返回的类型 把sql查询的结果封装到哪个实体类钟
#{id}===表示占位符等价于? 这是mybatis框架的语法
-->
<select id="findById" resultType="com.abc.entity.User">
select * from tb_user where userid=#{id}
</select>
<!--添加
parametertype: 参数类型
#{必须和属性对应}
-->
<insert id="add" parameterType="com.abc.entity.User">
insert into tb_user(username,realname) values(#{username},#{realname})
</insert>
<!--删除-->
<delete id="delete" parameterType="int">
delete from tb_user where userid=#{id}
</delete>
<!--修改-->
<update id="update" parameterType="com.abc.entity.User">
update tb_user set username=#{username},realname=#{realname} where userid=#{userid}
</update>
<!--查询所有-->
<select id="findAll" resultType="com.abc.entity.User">
select * from tb_user
</select>
</mapper>
6.测试
public class Test01 {
//查询所有
@Test
public void testFindAll()throws Exception{
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
SqlSession session=factory.openSession();
List<User> users = session.selectList("qy151.user.findAll");
System.out.println(users);
session.commit();//必须提交
session.close();
}
//修改
@Test
public void testUpdate()throws Exception{
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
SqlSession session=factory.openSession();
User user=new User(8,"cx","陈晓");
int row = session.update("qy151.user.update", user);
System.out.println(row);
session.commit();//必须提交
session.close();
}
//删除
@Test
public void testDelete()throws Exception{
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
SqlSession session=factory.openSession();
int row = session.delete("qy151.user.delete", 1);
System.out.println(row);
session.commit();//必须提交
session.close();
}
//测试添加
@Test
public void testAdd() throws Exception{
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
SqlSession session=factory.openSession();
User user=new User();
//user.setUsername("gqf");
//user.setRealname("顾千帆");
int row = session.insert("qy151.user.add", user);
System.out.println(row);
session.commit();//必须提交
session.close();
}
}
7. mybatis一些优化
7.1 为实体类起别名
mybatis.xml配置文件
<typeAliases>
<!--单独为某个实体类起别名 -->
<typeAlias type="com.abc.entity.User" alias="abc"/>
<!--为指定包下的实体类起别名该别名就是实体类名-->
<package name="com.abc.entity"/>
</typeAliases>
7.2 添加sql日志
(1)添加日志的jar
<typeAliases>
<!--单独为某个实体类起别名 -->
<typeAlias type="com.abc.entity.User" alias="abc"/>
<!--为指定包下的实体类起别名该别名就是实体类名-->
<package name="com.abc.entity"/>
</typeAliases>
(2)添加日志的文件配置
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
8. 通过dao和映射文件的关联来完成操作
8.1如何实现
(1)创建一个dao接口并定义自己需要的方法
public interface UserDao {
public List<User> findAll();
}
(2)创建映射文件
<?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">
<!--namespace:命名空间
必须和dao相同
-->
<mapper namespace="com.abc.dao.UserDao">
<select id="findAll" resultType="com.abc.entity.User">
select * from tb_user
</select>
</mapper>
注意: namespace必须和dao接口一样,而且标签的id必须和你接口的方法名一样。
(3)测试
@Test
public void testFindAll() throws Exception{
Reader resourceAsReader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(resourceAsReader);
SqlSession session=factory.openSession();
//获取相应接口的代理对象
UserDao userDao=session.getMapper(UserDao.class);
List<User> list = userDao.findAll();
System.out.println(list);
session.commit();
session.close();
}
8.2 安装mybatis插件
作用: 检查dao和映射文件是否匹配
9.传递多个参数
10.添加时如何返回递增的主键值
需要返回添加数据库后的id值
<!--添加用户
useGeneratedKeys:设置使用生成的主键
keyProperty: 赋值给哪个属性
-->
<insert id="addUser" parameterType="com.abc.entity.User"
useGeneratedKeys="true" keyProperty="userId">
insert into tb_user values(null,#{username},#{realname})
</insert>
11.解决列名和属性名不一致
问题: 查询时返回一个null,或者某个列没有值
可以有两种解决办法:
第一种: 为查询的列起别名 而别名和属性名一致
<!--根据id查询学生信息-->
<select id="findOne" resultType="com.abc.entity.Student">
select stu_id id,stu_name name,stu_age age from tb_stu where stu_id=#{id}
</select>
第二种: 使用resultMap完成列和属性之间的映射关系
<resultMap id="StuMapper" type="com.abc.entity.Student">
<!--主键的映射关系 column:列名 property:属性名-->
<id column="stu_id" property="id"/>
<!--普通列的映射关系-->
<result column="stu_name" property="name"/>
<result column="stu_age" property="age"/>
</resultMap>
<!--resultType和ResultMap二者只能用一个-->
<select id="findOne" resultMap="StuMapper">
select * from tb_stu where stu_id=#{id}
</select>
如果列名和属性名有些一致的,可以在resultMap中不写映射关系
12. 动态sql
12.1什么是动态sql
根据参数的值,判断sql的条件
name!=null address
select * from 表名 where name=#{name} and address=#{address}
name==null
select * from 表名
12.2mybatis中动态sql标签
12.2.1 if标签--单条件判断
//如果name不为null则按照name查询 如果为null则查询所有
public List<Account> findByCondition(@Param("name")String name,@Param("money") Double money);
<select id="findByCondition" resultType="com.abc.entity.Account">
select * from account where 1=1
<if test="name!=null and name!=''">
and name=#{name}
</if>
<if test="money!=null">
and money=#{money}
</if>
</select>
12.2.2 choose标签 多条件分支判断
<select id="findByCondition02" resultType="com.abc.entity.Account">
select * from account where 1=1
<choose>
<when test="name!=null and name!=''">
and name=#{name}
</when>
<when test="money!=null">
and money=#{money}
</when>
<otherwise>
and isdeleted=0
</otherwise>
</choose>
</select>
12.2.3 where标签
我们观察到上面的sql都加了 where 1=1 ,如果不使用where 1=1 那么你的动态sql可能会出错。 我们能不能不加where 1=1呢! 可以 那么我们就可以使用where标签,作用:可以自动为你添加where关键字,并且可以帮你去除第一个and |or
<select id="findByCondition" resultType="com.abc.entity.Account">
select * from account
<where>
<if test="name!=null and name!=''">
and name=#{name}
</if>
<if test="money!=null">
and money=#{money}
</if>
</where>
</select>
12.2.4 set标签
这个配合if标签一起用,一般用在修改语句。如果传递的参数值为null,那么应该不修改该列的值。
<!--set:可以帮我们生成关键字 set 并且可以去除最后一个逗号-->
<update id="update">
update account
<set>
<if test="name!=null and name!=''">
name=#{name},
</if>
<if test="money!=null">
money=#{money},
</if>
<if test="isdeleted!=null">
isdeleted=#{isdeleted},
</if>
<if test="created!=null">
created=#{created},
</if>
<if test="updated!=null">
updated=#{updated},
</if>
</set>
where id=#{id}
</update>
12.2.5 foreach标签
循环标签
查询:
<!-- select * from account where id in(2,3,5,7,0)
如果你使用的为数组array 如果你使用的为集合 那么就用list
collection:类型
item:数组中每个元素赋值的变量名
open: 以谁开始
close:以谁结束
separator:分割符
-->
<select id="findByIds" resultType="com.abc.entity.Account">
select * from account where id in
<foreach collection="array" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
删除:
<delete id="batchDelete">
<foreach collection="array" item="id" open="delete from account where id in(" close=")" separator=",">
#{id}
</foreach>
</delete>
添加:
insert into account(name,isdeleted) values('ldh',0),('ldh2',0),('ldh4',0)
<insert id="saveBatch">
insert into account(name,isdeleted) values
<foreach collection="list" item="acc" separator=",">
(#{acc.name},#{acc.isdeleted})
</foreach>
</insert>
13. sql片段
在执行查询语句时不建议使用select *, 建议使用sql片段
14. mybatis映射文件处理特殊字符
<!--
第一种:转义标签 <
第二种: <![CDATA[sql]]>
-->
<select id="findByMaxMin" resultType="com.abc.entity.Account">
<![CDATA[select * from account where id >#{min} and id <#{max}]]>
</select>
15. mybatis完成模糊查询
select * from 表名 where 列名 like '%a%'
(1)使用字符串函数 完成拼接 concat
<select id="findByLike" resultType="com.abc.entity.Account">
select * from account where name like concat('%',#{name},'%')
</select>
(2)使用${}
<select id="findByLike" resultType="com.abc.entity.Account">
select * from account where name like '%${name}%'
</select>
通过观察: 发现使用${}实际上是字符串拼接,它不能防止sql注入, 而#{}它是预编译,它可以防止sql注入问题,#{}实际使用的PreparedStatement
总结:
动态sql标签: if where (choose when otherwise) set foreach sql
处理特殊字符: <![CDATA[sql]]> 转义符
模糊查询: concat('',#{},'') ${}
16. 联表查询
多对一 : 从多的一方来查询一的一方
select * from tb_stu s join tb_class c on s.class_id=c.cid where stu_id=1
(1)实体类:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private int id;
private String name;
private int age;
private String sex;
private Integer classId;
private Clazz clazz;//学生所属的班级
}
//如何把联表查询体现到实体类上。
package com.abc.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Clazz {
private Integer cid;
private String cname;
}
(2)xml:
<resultMap id="baseMap" type="com.abc.entity.Student">
<id column="stu_id" property="id"/>
<result column="stu_name" property="name"/>
<result column="stu_age" property="age"/>
<result column="sex" property="sex"/>
<result column="class_id" property="classId"/>
<!--association: 表示一的一方
property: 它表示属性名
javaType: 该属性名对应的数据类型
-->
<association property="clazz" javaType="com.abc.entity.Clazz">
<id column="cid" property="cid"/>
<result column="cname" property="cname"/>
</association>
</resultMap>
<select id="findStudentById" resultMap="baseMap">
select * from tb_stu s join tb_class c on s.class_id=c.cid where stu_id=#{id}
</select>
(3)返回类型用map封装
//根据学生编号查询学员信息以及班级信息
public Map findById(Integer id);
<!--key:value-->
<select id="findById" resultType="java.util.Map">
select <include refid="aa"/> from tb_stu s join tb_class c on s.class_id=c.id where s.id=#{id}
</select>
17.分页插件PageHelper
分页语句:
select * from 表名 [where 条件] limit (page-1)*pageSize, pageSize;
page: 当前页码
pageSize: 每页显示的条数
(1)引入pageHelper的jar包
<!--引入pageHelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.11</version>
</dependency>
(2)mybatis中设置pageHelper的拦截器
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
(3)使用pageHelper
//设置分页属性pageNum:显示第几页 PageSize:每页显示的条数
PageHelper.startPage(2,5);
List<User> list = userDao.findAll();
//把查询的结果封装到PageInfo类中。
PageInfo<User> pageInfo=new PageInfo<User>(list);
System.out.println("总条数:"+pageInfo.getTotal());
System.out.println("总页数:"+pageInfo.getPages());
System.out.println("当前页码对应的数据:"+pageInfo.getList());
18.mybatis的代码生成器--generator
作用: 根据表帮你生成实体类,和dao和xml映射文件。就是简单的CRUD
官网:MyBatis Generator Core – Introduction to MyBatis Generator
(1)引入mybatis-generator的依赖jar包
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
(2)generator的配置文件
<!--mysql驱动jar的位置-->
<classPathEntry location="D:\repMaven\mysql\mysql-connector-java\8.0.20\mysql-connector-java-8.0.20.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<!--去除注释-->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据源的配置信息-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mysjk?serverTimezone=Asia/Shanghai"
userId="root"
password="128750">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--java实体类的配置-->
<javaModelGenerator targetPackage="com.wyn.entity" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--映射文件的配置-->
<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--dao数据访问层的配置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.wyn.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!--数据库表和实体的映射关系
schema:数据库名称
tableName: 表名
domainObjectName:实体类名
enableUpdateByExample:是否生成复杂的修改操作
-->
<table schema="mysjk" tableName="s_student" domainObjectName="Student"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
</context>
(3)运行配置文件
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
(4)去除注释
<!--去除注释-->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
19.mybatis的缓存
19.1 什么是缓存
缓存是存在于内存中的临时数据
mysql数据库中的数据存在----表--->磁盘上。 查询---程序IO读取磁盘的数据---添加--io向磁盘添加数据
19.2 缓存的好处
使用缓存减少和数据库的交互次数,提高执行效率
19.3 什么样的数据适合放入缓存
经常查询并且不经常改变的; 数据的正确与否对最终结果影响不大的;
19.4 什么样的数据不适合放入缓存
经常改变的数据; 数据的正确与否对最终结果影响很大的;---数据安全性要求不高。 例如:商品的库存,银行的汇率,股市的牌价;
19.5 mybatis缓存
mybatis支持两种缓存
(1)一级缓存----基于SqlSession级别的缓存。默认一级缓存是开启的,不能关闭。
(2)二级缓存--基于SqlSessionFactory级别的缓存,它可以做到多个SqlSession共享数据。默认它是关闭。需要手动开启。
19.5.1 演示一级缓存
//一级缓存---基于sqlSession完成的一级缓存
@Test
public void test1() throws Exception{
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = factory.openSession();
StudentMapper mapper = session.getMapper(StudentMapper.class);
Student student = mapper.selectByPrimaryKey(4);
System.out.println(student);
Student student2 = mapper.selectByPrimaryKey(4);
System.out.println(student2);
}
//一级缓存---基于sqlSession完成的一级缓存
@Test
public void test2() throws Exception{
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = factory.openSession();
StudentMapper mapper = session.getMapper(StudentMapper.class);
Student student = mapper.selectByPrimaryKey(4);
System.out.println(student);
session.close();
//开启新的SqlSession 重新发送申请
SqlSession session2 = factory.openSession();
StudentMapper mapper2 = session2.getMapper(StudentMapper.class);
Student student2 = mapper2.selectByPrimaryKey(4);
System.out.println(student2);
}
19.5.2 演示二级缓存
(1)开启二级缓存
<settings>
<!--开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
(2)在映射文件中使用二级缓存
<!--使用二级缓存 这里面的所有查询都使用了二级缓存-->
<cache/>
(3)实体一定要实现序列化接口
(4)测试二级缓存
//二级缓存---基于SqlSessionFactory
@Test
public void test3() throws Exception{
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = factory.openSession();
StudentMapper mapper = session.getMapper(StudentMapper.class);
Student student = mapper.selectByPrimaryKey(4);
System.out.println(student);
session.close();//关闭
//开启新的SqlSession 重新发送申请
SqlSession session2 = factory.openSession();
StudentMapper mapper2 = session2.getMapper(StudentMapper.class);
Student student2 = mapper2.selectByPrimaryKey(4);
System.out.println(student2);
查询顺序: 二级缓存----一级缓存----数据库