MyBatis
1.简介
1.1什么是MyBatis
- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- MyBatis本是apache开源项目iBatis,后迁移到google code改名为MyBatis,现在Github
1.2如何获得MyBatis
Maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
1.3持久层
- 持久化
数据持久化:将程序的数据在持久状态和瞬时状态转换的过程
- 持久层
-
- 完成持久化工作的代码
- 层界限十分明显
1.4为什么需要MyBatis
- 帮助程序员将数据存入到数据库中
- 方便
- 传统的JDBC代码太复杂了,需要简化
- sql与代码分离,提高了可维护性
2.初识MyBatis
2.1实践
一.搭建环境
1.搭建数据库,建表
user表:id,name,pwd
2.新建项目
2.1 新建一个普通的maven项目,删除src目录
2.2导入依赖(一定要先删掉官方配置中的mapper标签,后续自己添加)
- mysql
- mybatis
- junit
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
2.3连接数据库
填写user和密码,选择schemas,选择要连接的数据库,apply,ok
3.创建一个模块
- 编写mybatis核心配置文件==“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>
<environments default="development">
<environment id="development">
<!--事务管理-->
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
- 编写mybatis工具类
/**
* 工具类sqlSessionFactory->sqlSession
*/
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try{
//使用Mabatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e){
e.printStackTrace();
}
}
/**
* 既然有了sqlSessionFactory,我们就可以从中获取sqlsession的实例了
* sqlsession完全包含了面向数据库执行SQL命令所需的所有方法
*/
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
- SqlSessionFactoryBuilder:一旦创建了SqlSessionFactory就不再需要他了,因为SqlSessionFactoryBuilder实例的最佳作用域是方法作用域
- SqlSessionFactory:一旦被创建就在应用的运行期间一直存在,作用域是应用作用域
- SqlSession:每个线程都应该有他的SqlSession实例。每次收到一个HTTP请求,就可以打开一个SqlSession,返回一个响应,就要关闭他。
4.编写代码
- 实体类(与数据库表中字段一一对应)
/**
* 实体类
*/
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String toString(){
return "User{"+"id="+id+"name="+name+"pwd="+pwd+"}";
}
}
- Dao接口(对实体类的操作定义,增删改查等)
public interface UserMapper {
List<User> getUserList();
}
- 接口实现类(以往用java代码使用jdbc编写,现在用mapper配置文件代替实现类)
<?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接口-->
<mapper namespace="com.yangtuo.dao.UserMapper">
<!-- 查询语句;id:对应接口中的方法名;resultType:返回值类型-->
<select id="getUserList" resultType="com.yangtuo.pojo.User">
select * from mybatis.user
</select>
</mapper>
5.测试
public class UserDaoTest {
@Test
public void test(){
//第一步:获得sqlsession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//执行sql,注意这里的UserMapper是接口
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭sqlsession
sqlSession.close();
}
}
注意
要在pom.xml中加入过滤,否则找不到自编的配置文件
<!-- 在build中配置resources,来防止我们资源导出失败问题-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
同时,由于之前mybatis-config.xml中删除了mapper标签,这里要补回来,添加
<?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"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/yangtuo/dao/UserMapper.xml"/>
</mappers>
</configuration>
注意:这里的resource中一定要是‘/’
2.2 CRUD增删改查
1.namespace
namespace中的包名和对应的接口名一致
2.select
选择查询语句:
- id:方法名
- resultType:结果返回值
- parameterType:参数类型
3.整体测试
- 只需要修改接口UserMapper,添加Mapper.xml中对应的实现方法,编写测试类
-
定义接口
public interface UserMapper { //查询全部用户 List<User> getUserList(); //根据id查询用户 User getUserById(int id); //增加一个用户 int addUser(User user); //修改用户 int updateUser(User user); //删除一个用户 int deleteUser(int id); }
-
在xml中实现接口
<!--namespace:命名空间,绑定一个对应的Dao/Mapper接口--> <mapper namespace="com.yangtuo.dao.UserMapper"> <!-- 查询语句;id:对应接口中的方法名--> <select id="getUserList" resultType="com.yangtuo.pojo.User"> select * from mybatis.user </select> <select id="getUserById" resultType="com.yangtuo.pojo.User" parameterType="int"> select * from mybatis.user where id = #{id} </select> <insert id="addUser" parameterType="com.yangtuo.pojo.User"> insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd}); </insert> <update id="updateUser" parameterType="com.yangtuo.pojo.User"> update mybatis.user set name =#{name},pwd=#{pwd} where id = #{id} </update> <delete id="deleteUser" parameterType="int"> delete from mybatis.user where id = #{id} </delete> </mapper>
-
编写测试类
public class UserDaoTest { @Test public void test(){ //第一步:获得sqlsession对象 SqlSession sqlSession = MyBatisUtils.getSqlSession(); //执行sql UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.getUserList(); for (User user : userList) { System.out.println(user); } //关闭sqlsession sqlSession.close(); } @Test public void getUserById(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(2); System.out.println(user); sqlSession.close(); } @Test public void addUser(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int res = mapper.addUser(new User(4,"wangwu","1452")); if(res>0){ System.out.println("插入成功"); } //提交事务 sqlSession.commit(); sqlSession.close(); } @Test public void updateUser(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.updateUser(new User(4,"hehe","123123")); sqlSession.commit(); sqlSession.close(); } @Test public void deleteUser(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.deleteUser(4); sqlSession.commit();; sqlSession.close(); } }
注意:在增删改后一定要提交事务,否则无法做出修改
-
-
2.3万能Map
1.定义接口方法
//万能的Map
User getUserById2(Map<String,Object> map);
2.去Mapper中实现方法
<select id="getUserById2" resultType="com.yangtuo.pojo.User" parameterType="map">
select * from mybatis.user where id = #{id} and name = #{name}
</select>
3.测试方法
@Test
public void getUserById2(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("id","1");
map.put("name","姜吉宁");
User user = mapper.getUserById2(map);
System.out.println(user);
sqlSession.close();
}
注意:这里的map中的key要和Mapper中占位符中的参数相同
区别:
- 使用Map传递参数,只需要在sql中取出key即可
- 使用对象传递参数,直接在sql中取出对象的属性(属性名要和Mapper中占位符中的参数相同)
- 只有一个基本类型参数的情况下,可以直接在sql中取到
- 多个参数用Map或注解(现在还没学)
2.4模糊查询
Java代码执行的时候,传递通配符%,也可以在sql中使用通配符
1.定义接口方法
//模糊查询用户
List<User> getUserLike(String value);
2.去Mapper中实现方法
<select id="getUserLike" resultType="com.yangtuo.pojo.User">
select * from mybatis.user where name like #{value}
</select>
3.测试方法
@Test
public void getUserLike(){
//第一步:获得sqlsession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserLike("李%");
for (User user : userList) {
System.out.println(user);
}
//关闭sqlsession
sqlSession.close();
}
3.配置解析
1、核心配置文件
- Mybatis-config.xml
- MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
2.环境配置(environments)
MyBatis可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
MyBatis默认的事物管理器是JDBC,数据源类型:默认使用连接池,POOLED
3.属性(properties)
我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。
1.编写一个数据库配置文件db.properties注意:这里面url中没有转义字符,又会报错;driver中要写mysql8格式的driver
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
name=root
password=123456
2.在核心配置文件中映入——引入properties(虽然在property和environment中都配置了name,pwd,但会先走environment)
注意:xml中标签是有顺序的,properties一定要放在最上面
<!-- 引入外部配置文件-->
<properties resource="db.properties">
<property name="name" value="root"/>
<property name="pwd" value="111"/>
</properties>
<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="${name}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
4.类型别名
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
方法一:为每个类指定别名(在mybatis-config.xml(主配置文件)中)
<!-- 可以给实体类起别名-->
<typeAliases>
<typeAlias type="com.yangtuo.pojo.User" alias="User"/>
</typeAliases>
加上别名后,User可以用在任何使用com.yangtuo.pojo.User的地方
方法二:指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,它的默认别名是这个类名的首字母小写形式
<!-- 扫描实体类的包,默认别名为这个类的类名首字母小写-->
<typeAliases>
<package name="com.yangtuo.pojo"/>
</typeAliases>
在实体类比较少的时候,使用第一种方式
如果实体类十分多,使用第二种
第一种可以diy别名,第二种不行,但是可以在实体类上加注解指定别名,比如:
@Alias("user")
public class User {
5.设置
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为
6.映射器(mappers)
MapperRegistry:注册绑定我们的Mapper文件
方式一:使用xml实现
<!--每一个Mapper.xml都要在MyBatis核心配置文件中注册-->
<mappers>
<mapper resource="com/yangtuo/dao/UserMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册(class中时接口的地址)
<mappers>
<mapper class="com.yangtuo.dao.UserMapper"/>
</mappers>
注意点
- 接口和它的Mapper配置文件要同名
- 接口和它的Mapper配置文件必须放在同一包下
方式三:使用扫描包进行注入绑定
<mappers>
<package name="com.yangtuo.dao"/>
</mappers>
7.生命周期和作用域
不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder:
- 一旦创建了 SqlSessionFactory,就不再需要它了。
- 最佳作用域是方法作用域,也就是局部变量
SqlSessionFactory:
- 可以想象为数据库连接池
- 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
- 最佳作用域是应用作用域
- 最简单的就是使用单例模式或者静态单例模式
SqlSession:
-
可以想象为连接到连接池的一个请求
-
需要开启和关闭
-
每个线程都应该有它自己的 SqlSession 实例。
-
SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
Mapper:
相当于一个具体业务
4.解决属性名和字段名不一致的问题
1.数据库中字段:id,name,pwd
2.新建一个项目,修改字段
public class User {
private int id;
private String name;
private String password;
测试出现问题
解决方法——ResultMap
resultMap
元素是 MyBatis 中最重要最强大的元素。
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
结果集映射
<!-- 结果集映射-->
<resultMap id="userMap" type="user">
<!-- column:对应数据库中字段;property:对应实体类中属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<!--甚至可以只要这一句,因为只有这一句数据库与实体类字段不一致-->
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" resultMap="userMap" parameterType="user">
select * from mybatis.user where id = #{id}
</select>
5.日志
5.1日志工厂
如果数据库操作出现异常,需要排错,日志是最好的助手
曾经:sout,debug
现在:日志工厂
重点掌握:LOG4J,STDOUT_LOGGING
在mybatis中具体使用那个日志实现在设置中设定
1.STDOUT_LOGGING
在mybatis-config.xml核心配置文件中设置(注意要在properties后面)
<!-- 设置日志工厂-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
日志输出
2.LOG4J
1.导入包
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
2.log4j.properties
# 全局日志配置,将等级为debug的日志信息输出到console和file这两个目的地
log4j.rootLogger = DEBUG,Console,file
# MyBatis 日志配置
log4j.logger.Mapper=DEBUG
# 控制台输出
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.Treshold=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/yangtuo.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
3.配置log4j为日志的实现
<!-- 设置日志工厂-->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
4.LOG4J的使用,直接运行测试类
5.简单使用
5.1 在要使用Log4j的类中,导入包
import org.apache.log4j.Logger;
5.2 日志对象加载参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
5.3日志级别
@Test
public void testLog4j(){
logger.info("进入了testlog4j方法");
logger.debug("debug进入了");
logger.error("error:进入testlog4j");
}
以后在测试时需要输出日志信息只需在原sout的地方使用logger即可
6.分页
1.为什么分页?
- 减少数据的处理量
使用limit分页
select * from user limit startindex,pagesize
使用mybatis实现分页
**第一步:**写使用limit查询接口
//使用limit查询
List<User> getUserByLimit(Map<String,Integer> map);
**第二步:**写usermapper.xml中的sql语句
<select id="getUserByLimit" parameterType="map" resultMap="userMap">
select * from mybatis.user limit #{startindex},#{pagesize}
</select>
<!-- 结果集映射,因为实体类中的字段和数据库中字段不统一-->
<resultMap id="userMap" type="user">
<!-- column:对应数据库中字段;property:对应实体类中属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
**第三步:**写测试方法
@Test
public void getUserByLimit(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("startindex",0);
hashMap.put("pagesize",2);
List<User> userList = mapper.getUserByLimit(hashMap);
for (User user : userList) {
System.out.println(user);
}
//关闭sqlsession
sqlSession.close();
}
使用RowBounds分页
**第一步:**写使用RowBounds查询接口
//使用RowBounds查询
List<User> getUserByRowBounds();
**第二步:**写usermapper.xml中的sql语句
<select id="getUserByRowBounds" resultMap="userMap">
select * from mybatis.user
</select>
**第三步:**写测试方法
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
RowBounds rowBounds = new RowBounds(1, 2);
//通过java代码层面实现
List<User> userList = sqlSession.selectList("com.yangtuo.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
7.使用注解开发
7.1面向接口编程——解耦
省略userMapper.xml,直接在接口方法上引入注解,并在括号中写sql语句
7.2CRUD
1.我们可以在工具类创建的时候实现事务的自动提交,true
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
2.编写接口,添加注解
public interface UserMapper {
//查询全部用户
@Select("select * from user")
List<User> getUserList();
//根据id查询用户
@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 addUser2(User user);
//修改用户
@Update("update user set name=#{name} where id=#{id}")
int updateUser2(User user);
//删除一个用户
@Delete("delete from user where id=#{id}")
int deleteUser2(@Param("id") int id);
//使用limit查询
List<User> getUserByLimit(Map<String,Integer> map);
//使用RowBounds查询
List<User> getUserByRowBounds();
}
3.编写测试类
public class userMapperTest {
@Test
public void getUserList(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getUserById(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(2);
System.out.println(user);
sqlSession.close();
}
@Test
public void addUser2(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser2(new User(5,"liuliu","123456789"));
sqlSession.close();
}
@Test
public void updateUser2(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser2(new User(5,"niuniu","null"));
sqlSession.close();
}
@Test
public void delete2(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser2(5);
sqlSession.close();
}
}
关于@Param()注解
- 基本类型和String类型需要加,引用类型不需要加
- 如果只有一个基本类型的话,可以忽略,但是建议加上
- 我们在sql中引用的,就是这里的@Param()中设定的属性名
8.Lombok
Project Lombok是一个java库,它会自动插入到你的编辑器和构建工具中,为你的java增添色彩。
再也不用编写另一个 getter 或 equals 方法,只需一个注解,您的类就会有一个功能齐全的构建器,自动执行日志记录变量等等。
1. 使用步骤
步骤一:安装lombok插件
在file,settings, plugins,搜lombok,现在已经是内置插件了
步骤二:在项目中导入jar包
<dependencies>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
</dependencies>
步骤三:在实体类中使用
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String password;
}
效果:使用@Data(lombok中的注解)注解自动实现了getter,setter,无参构造器,hashcode,eqauls,toString等方法
使用@AllArgsConstructor生成有参构造方法,但是加上这个之后无参构造就没了,
可以再加一个注解@NoArgsConstructor将无参构造加回来
9.多对一查询处理
准备(多对一映射)
@Data
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private Teacher teacher;
}
@Data
public class Teacher {
private int id;
private String name;
}
1.按照查询嵌套处理(相当于子查询)
查询所有学生信息及对应老师的姓名
步骤一:在学生和老师接口中要有查询所有学生和根据id査老师的方法
//查询所有的学生信息
public List<Student> getStudent();
//根据id查老师
Teacher getTeacher(int id);
步骤二:在mapper中写sql语句
<!--查找学生及其对应的老师的姓名
1.查找所有学生信息
2.根据查出来学生的tid,寻找对应的老师-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<!--结果集映射,在映射中添加查询老师的select语句-->
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性,我们需要单独处理 对象:association,不光要字段和数据库对应,还要添加javatype和select语句 集合:collection-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
<!--这里的#{id}只是一个占位符,填啥都行,但最好是统一-->
select * from teacher where id=#{id};
</select>
步骤三:测试
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> student = mapper.getStudent();
for (Student student1 : student) {
System.out.println(student1);
}
sqlSession.close();
2.按照结果嵌套处理
<!-- 按照结果嵌套处理-->
<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="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
10.一对多查询处理
准备(一对多映射)
@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> studentList;
}
@Data
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private int tid;
}
1.按照查询嵌套处理(相当于子查询)
有两条查询语句,一个主查询,一个子查询
<select id="getTeacherById2" resultMap="StudentTeacher">
select * from teacher where id = #{tid};
</select>
<resultMap id="StudentTeacher" type="Teacher">
<collection property="studentList" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid = #{tid}
</select>
2.按照结果嵌套处理
简单来说就是只有一条查询语句
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--因为学生是一个集合,所以要用collection获取
javaType用来指定属性的类型
集合中的泛型信息,我们用ofType来获取-->
<collection property="studentList" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
</collection>
</resultMap>
<select id="getTeacherById" 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 = #{tid};
</select>
小结
- 关联:association 多对一
- 集合:collection 一对多
- javaType:用来指定实体类中属性的类型
- ofType:用来指定映射到List或集合中的pojo类型,泛型中的约束类型
11.动态SQL
什么是动态sql:指根据不同的条件生成不同的sql语句
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
1.搭建环境
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;
创建一个基础工程
1.导包
2.编写配置文件
3.编写实体类
@Data
public class Blog {
private int id;
private String tile;
private String author;
private Date createTime;
private int views;
}
4.编写实体类对应的Mapper接口和Mapper.xml文件
2.标签
IF
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog
<where>
<if test="title !=null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</where>
</select>
@Test
public void queryBlog(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","微服务");
map.put("author","狂神说");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
choose (when, otherwise)
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from 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>
@Test
public void queryBlogChoose(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","微服务");
map.put("author","狂神说");
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
trim (where, set)
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author!=null">
author=#{author},
</if>
</set>
where id=#{id}
</update>
@Test
public void updateBlog(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("id","191e7e466c854f819228f0bc299ba31a");
map.put("title","微服务");
map.put("author","狂神说");
mapper.updateBlog(map);
sqlSession.commit();
sqlSession.close();
}
FOREACH
<!--
select * from blog where 1=1 and (id=1 or id=2 or id=3)
传递一个万能的map,这个map中可以存在一个集合
-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<>();
ids.add(1);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
SQL片段
有时,会将一些功能抽取出来,方便复用
- 使用SQL标签抽取公共的部分
<sql id="if-title-author">
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</sql>
- 在需要使用的地方使用include标签即可
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
注意事项:
- 最好基于单表来定义SQL片段
- 不要存在where标签,最好用if标签,复用性高
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
- 先在mysql中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可!
12.缓存
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启(sqlsession级别的缓存,也成为了本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存
- 为了提高扩展性,mybatis定义了缓存接口Cache,我们可以实现cache接口来自定义二级缓存
1.一级缓存
测试步骤:
步骤一:开启日志
<setting name="logImpl" value="STDOUT_LOGGING"/>
步骤二:测试在一个session中查询两次相同记录
@Test
public void test(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
User user2 = mapper.getUserById(1);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
}
步骤三:查看日志记录
缓存失效的情况
-
查询不同的东西
-
增删改操作,可能改变原来的数据,所以必定会刷新缓存
@Test public void test(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); mapper.updateUser(new User(2,"jgh","12354")); User user2 = mapper.getUserById(1); System.out.println(user2); System.out.println(user==user2); sqlSession.close(); }
-
查询不同的Mapper.xml
-
手动清理缓存
sqlSession.clearCache();//手动清理缓存
小结:
- 一级缓存默认是开启的,只在一次sqlsession中有效,也就是拿到连接到关闭连接这个时间段
2.二级缓存
工作机制:
- 一个会话查询一条数据,这个数据会被放到当前会话的一级缓存中
- 如果当前会话关闭,一级缓存就没了;但我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己对应的缓存(map)中
步骤一:开启全局缓存
<!--显示开启全局缓存-->
<setting name="cachedEnabled" value="true"/>
步骤二:在要使用二级缓存的mapper.xml中开启
<!--在当前mapper.xml中使用二级缓存
可以自定义参数-->
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
步骤三:测试
@Test
public void test(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
SqlSession sqlSession2 = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 = mapper2.getUserById(1);
System.out.println(user2);
System.out.println(user==user2);
sqlSession2.close();
}
步骤四:结果
sqlsession的时候,连接数据库并查询出结果,然后sqlsession会话关闭,然后sqlsession2查同样的数据,这样,由于开启了二级缓存,缓存命中,不需要查询数据库
小结:
- 只要开启了二级缓存,在同一个mapper下就有效
- 所有的数据都会先放到一级缓存中
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存中