SSM-MyBatis
【MyBatis】学习笔记来源于==【狂神说Java】Mybatis最新完整教程IDEA版通俗易懂==
【编写MyBatis项目的基本步骤】
*0、常用配置
0.1、父类pom.xml常用配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 父工程 -->
<groupId>com.pmpwpl</groupId>
<artifactId>mybatis-study</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<!-- 这些都是子工程 -->
<module>mybatis-01</module>
<module>mybatis-02</module>
<module>mybatis-03</module>
<module>mybatis-04</module>
<module>mybatis-05</module>
<module>mybatis-06</module>
<module>mybatis-07</module>
<module>mybatis-08</module>
<module>mybatis-09</module>
</modules>
<!-- 导入依赖 -->
<dependencies>
<!-- 导入mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 导入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>
<!--导入lombok包-->
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>
<!-- 在build中配置resources , 来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
0.2、子类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核心配置文件 -->
<configuration>
<!-- 引入数据库配置文件 -->
<properties resource="db.properties"/>
<settings>
<!--设置标准日志输出-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--开启自动驼峰命名-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--配置缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- 可以给实体类起别名 -->
<typeAliases>
<typeAlias type="com.pmpwpl.pojo.Blog" alias="Blog"/>
<package name="com.pmpwpl.pojo.Blog"/>
</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.pmpwpl.dao.BlogMapper"/>
</mappers>
</configuration>
0.3、子类MyBatisUtils.java常用配置
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();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 org.apache.ibatis.jdbc.SQL 命令所需的所有方法。
//你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);//设置为true,自动提交事务
}
}
0.4、子类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.pmpwpl.dao.UserMapper">
<!--在当前mapper中开启二级缓存-->
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
</mapper>
0.5、junit测试
@Test
public void test(){
//第一步获取sqlSession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//方式一:getMapper()
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
//方式二:这种方法不怎么用,一般都用第一种
//List<User> userList = sqlSession.selectList("com.pmpwpl.dao.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user);
}
//关闭sqlSession对象
sqlSession.close();
}
1、简介
1.1、什么是MyBatis
- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis 。
- 2013年11月迁移到Github。
如何获得MyBtis?
1.2、持久化
数据持久化
持久化就是将程序的数据的持久状态和瞬时状态转化的过程
数据库(JDBC)、io文件持久化
为什么需要持久化?因为内存断电即失,一些数据不能流失、内存价格昂贵
1.3、持久层
Dao层、Service层、Controller层
- 完成持久化工作的代码
- 层界限十分明显
1.4、为什么需要MyBatis?
- 方便
- 帮助程序员将数据存入数据库
- 传统的JDBC代码复杂,简化,框架,自动化
- 使用的人多
2、第一个MyBatis程序
mybatis-01
思路:搭建环境 --> 导入MyBatis --> 编写代码 --> 测试
2.1、搭建环境
搭建数据库
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE USER(
id INT(20) NOT NULL PRIMARY KEY,
NAME VARCHAR(30) NOT NULL,
pwd VARCHAR(30) NOT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO USER(id,NAME,pwd) VALUES
(1,'栾勇','123456'),
(2,'栾康','123456'),
(3,'李开民','123456')
新建项目
-
新建一个普通的maven项目,不选任何模块
-
删除src目录
-
在父类pom.xml中导入maven依赖
<!-- 导入依赖 --> <dependencies> <!-- 导入mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</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>
-
在父类pom.xml文件中的依赖后面配置resouces
<!-- 在build中配置resources , 来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
2.2、创建一个模块
-
编写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核心配置文件 --> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis? useUnicode=true&characterEncoding=UTF-8&useSSL=true"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!-- 每一个Mapper配置文件都必须注册! --> <mappers> <mapper resource="com/pmpwpl/dao/UserMapper.xml"/> </mappers> </configuration>
-
编写mybatis工具类【MyBatisUtils.java】
//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();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 org.apache.ibatis.jdbc.SQL 命令所需的所有方法。
//你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
//上面这一句相当于下面的
//SqlSession sqlSession = sqlSessionFactory.openSession();
//return sqlSession;
}
}
2.3、编写代码
-
实体类【User】
//实体类 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; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
-
Dao类【接口】
//Dao/Mapper类 public interface UserDao { List<User> getUserList(); }
-
接口实现类,由原来的UserDaoImpl转变为Mapper配置文件【UserMapper.xml文件】
<?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.pmpwpl.dao.UserMapper"> <!-- select查询语句 --> <select id="selectUsers" resultType="com.pmpwpl.pojo.User"> select * from mybatis.user; </select> </mapper>
2.4、测试
常见错误:
- org.apache.ibatis.binding.BindingException: Type interface com.pmpwpl.dao.UserDao is not known to the MapperRegistry.
<!-- 每一个Mapper配置文件都必须注册! -->
<mappers>
<mapper resource="com/pmpwpl/dao/UserMapper.xml"/>
</mappers>
-
com.pmpwpl.dao.UserDaoTest
<!-- 在build中配置resources , 来防止我们资源导出失败的问题--> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> </resources> </build>
junit测试
public class UserDaoTest {
@Test
public void test(){
//第一步获取sqlSession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//方式一:getMapper()
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
//方式二:这种方法不怎么用,一般都用第一种
//List<User> userList = sqlSession.selectList("com.pmpwpl.dao.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user);
}
//关闭sqlSession对象
sqlSession.close();
}
}
可能遇到的问题:
- 配置文件没有注册
- 绑定接口错误
- 方法名不对
- 返回类型不对
- Maven导出资源问题
3、CURD增删改查
3.1、namespace
namespace中的包名要和Dao/Mapper中的一致
3.2、select查询
select是选择查询语句
- id:就是对应的namespace中的方法名
- resultTpye:Sql语句执行的返回值类型
- paramaterTpye:参数类型
@Test //查询所有User
public void testAll(){
//第一步获取sqlSession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//方式一:getMapper()
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
//方式二:
//List<User> userList = sqlSession.selectList("com.pmpwpl.dao.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user);
}
//关闭sqlSession对象
sqlSession.close();
}
3.3、delete删除
@Test //根据ID删除User
public void textById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.delById(8);
if(res > 0){
System.out.println("删除成功");
}
//提交事务
sqlSession.commit();
testAll();
//关闭sqlSession对象
sqlSession.close();
}
3.4、insert增加
@Test //添加User
public void testAddUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.addUser(new User(4, "栾勇", "6666"));
if(res > 0){
System.out.println("添加成功");
}
sqlSession.commit();
testAll();
sqlSession.close();
}
3.5、update修改
@Test //根据ID修改User
public void testUpById()
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int upById = mapper.UpById(new User(1,"李开民","123456789"));
if(upById > 0){
System.out.println("修改成功");
}
sqlSession.commit();
testAll();
sqlSession.close();
}
注意点:
- 增删改需要添加事务
3.6、错误分析
- 标签不要匹配错误
- resources绑定Mapper,需要使用路径
- 程序配置文件必须符合规范
3.7、万能Map
实体类或者数据库的表中,有很多的参数或者很多的字段,这时候可以考虑使用Map,下面对应着
//使用Map添加User
int addByMap(Map<String,Object> map);
<!-- 使用Map添加User -->
<insert id="addByMap" parameterType="map">
insert into mybatis.user(id, name, pwd) VALUES (#{userId},#{userName},#{userPwd});
</insert>
@Test //使用Map添加user
public void testaddByMap(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map = new HashMap<String, Object>();
map.put("userId",14);
map.put("userName","邢新宇");
map.put("userPwd","555555666666");
int addByMap = mapper.addByMap(map);
if(addByMap > 0){
System.out.println("Map添加成功");
}
sqlSession.commit();
testAll();
sqlSession.close();
}
- Map传递参数,直接在sql中取出key即可!
- 对象传递参数,直接在sql中取对象的属性即可!
- 只有一个基本类型的参数的情况下,可以直接到sql中取到
- 多参数用Map或者注解
3.8、模糊查询
//模糊查询
List<User> getUserLike(String value);
<!-- 模糊查询 -->
<select id="getUserLike" resultType="com.pmpwpl.pojo.User">
select * from mybatis.user where name like "%" #{value} "%"
</select>
@Test //模糊查询
public void getUserLike() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userLike = mapper.getUserLike("栾");
for (User user : userLike) {
System.out.println(user);
}
sqlSession.close();
}
4、配置解析
4.1、核心配置文件
-
mybatis-config.xml
-
MyBatisd的配置文件包含了会深深影响MyBatis行为的设置和属性信息
configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
4.2、环境配置(environments)
MyBatis可以配置成适应多种环境,使用时每次只能选择一个
学会使用配置多套运行环境
MyBatis默认的事物管理器就是JDBC,连接池: POOLED
4.3、属性(properties)
可以通过properties属性来实现引用配置文件,核心配置文件中应遵循这样的一个顺序:
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties】
-
编写[db.properties]文件,在resources文件夹下
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&useSSL=true username=root password=root
-
在核心配置文件中引入
<!-- 引入配配置文件 --> <properties resource="db.properties"/>
4.4、类型别名(typeAliases)
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
<!-- 可以给实体类起别名 -->
<typeAliases>
<typeAlias type="com.pmpwpl.pojo.User" alias="User"/>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
扫描实体类时,他的默认的别名就是他的类名,首字母小写
<!-- 可以给实体类起别名 -->
<typeAliases>
<package name="com.pmpwpl.pojo"/>
</typeAliases>
4.5、设置(settings)
这是MyBatis中极为重要的的调整设置,它会改变MyBatis运行时的行为
4.6、映射器(mappers)
方式一:【推荐使用】
<!-- 使用相对于类路径的资源引用 -->
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
<mapper class="org.mybatis.builder.AuthorMapper"/>
<mapper class="org.mybatis.builder.BlogMapper"/>
<mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
注意点:
- 接口和它的Mapper.xml配置文件必须同名
- 接口和它的Mapper.xml配置文件必须在同一个包下
方式三:使用扫描包注入绑定
<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
<package name="org.mybatis.builder"/>
</mappers>
注意点:
- 接口和它的Mapper.xml配置文件必须同名
- 接口和它的Mapper.xml配置文件必须在同一个包下
4.8、生命周期和作用域(Scope)
生命周期和作用域是至关重要的,错误的用法会导致严重的并发问题。
SqlSessionFactoryBulider:
- 一旦创建SqlSessionFactory,就不再需要它了
- 局部变量
SqlSessionFactory:
- 说白了可以想象为数据库连接池
- SqlSessionFactory一旦被创建就应该在应用运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
- 最佳作用域是应用作用域
- 最简单的就是使用单例模式或者静态单例模式
SqlSession:
- 连接到连接池的一个请求
- SqlSession的实例不是线程安全的,因此不能被共享,最佳作用域是请求或方法作用域
- 用完之后赶紧关闭,否则资源被占用!
这里面每一个Mapper就代表一个具体业务
5、ResultMap
用于解决属性名和字段名不一致的问题
属性为
private int id;
private String name;
private String password;
password属性与字段不一致,字段为pwd
测试时会出现问题:出现空值现象
User{id=1, name='栾勇', password='null'}
解决方法:
-
起别名:pwd as password
User{id=1, name='栾勇', password='123456'}
-
结果集映射
<!--结果集映射--> <resultMap id="userMap" type="User"> <!--column:数据库中的字段--> <!--property:实体类中的属性--> <result column="id" property="id"/> <result column="name" property="name"/> <result column="pwd" property="password"/> </resultMap> <!-- 根据ID查询User --> <select id="getUserById" resultMap="userMap"> select * from mybatis.user where id = #{id}; </select>
resultMap
元素是 MyBatis 中最重要最强大的元素。- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
- 引用它的语句中设置
resultMap
属性就行了(注意我们去掉了resultType
属性) - 如果这个世界总是这么简单就好了。
6、日志
6.1、标准日志工厂
如果一个数据库操作,出现了错误,我们需要排错,日志是最好的助手
- SLF4J
- LOG4J 【掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING 【掌握】
- NO_LOGGING
在MyBatis中具体使用哪一个日志,在设置中设定
STDOUT_LOGGING标准日志输出
在MyBatis核心配置文件中,配置日志,【注意:】一个空格都不能有
<!--设置标准日志输出-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
6.2、LOG4J
什么是log4j?
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件。
- 我们也可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
- 最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
-
在当前Moudle模块下,配置LOG4J依赖
<!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
-
配置log4j.properties【没有配置文件就上网搜】
-
配置log4j为日志的实现
<!--配置LOG4J日志实现--> <settings> <setting name="logImpl" value="LOG4J"/> </settings>
7、分页
思考:为什么要分页?
- 减少数据的处理量
7.1、使用limit分页
使用limit分页:语法如下:
select * from user limit startIndex,pageSize;
使用MyBatis实现分页,核心SQL语句
-
接口
//分页查询 List<User> getList(Map<String,Integer> map);
-
Mapper.xml
<!--分页查询--> <select id="getList" parameterType="Map" resultMap="userMap"> select * from mybatis.user limit #{startIndex},#{pageSize}; </select>
-
测试
@Test //分页查询 public void getList(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("startIndex",0); map.put("pageSize",2); List<User> users = mapper.getList(map); for (User user : users) { System.out.println(user); } sqlSession.close(); }
7.2、使用RowBounds分页
核心java代码
-
接口
//分页2 List<User> getUserByRowBounds();
-
Mapper.xml
<!--分页2--> <select id="getUserByRowBounds" resultType="user"> select * from mybatis.user; </select>
-
测试
@Test //分页查询2 public void getUserByRowBounds(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); //RowBounds实现 RowBounds rowBounds = new RowBounds(1, 2); //通过java代码层面实现分页 List<User> list = sqlSession.selectList("com.pmpwpl.dao.UserMapper.getUserByRowBounds", null, rowBounds); for (User user : list) { System.out.println(user); } sqlSession.close(); }
7.3、分页插件
8、使用注解开发
8.1、使用注解开发
-
接口
//根据ID查询User @Select("select * from mybatis.user") List<User> getUsers();
-
在mybatis-config.xml文件中绑定接口
<!--绑定接口--> <mappers> <mapper class="com.pmpwpl.dao.UserMapper"/> </mappers>
-
测试
@Test //使用注解查询全部 public void getUsers(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.getUsers(); for (User user : users) { System.out.println(user); } sqlSession.close(); }
本质:反射机制实现
底层:动态代理
8.2、CRUD
可以在工具类创建时实现自动提交事务
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
编写接口,增加注解
public interface UserMapper {
//查询全部
@Select("select * from mybatis.user")
List<User> getUsers();
//根据ID查询,有多个参数时,必须加上@Param()注解
@Select("select * from user where id = #{id}")
User getUser(@Param("id") int id);
//添加
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{password})")
int insertUser(User user);
//根据ID删除
@Delete("delete from user where id = #{id}")
int deleteUser(@Param("id") int id);
//修改
@Update("update user set name = #{name},pwd = #{password} where id = #{id}")
int updateUser(User user);
}
【注意】:必须在mybatis-config.xml中绑定接口
<!--绑定接口-->
<mappers>
<mapper class="com.pmpwpl.dao.UserMapper"/>
</mappers>
关于@Param()注解
- 基本类型的参数或String类型需要加上
- 引用类型不需要加
- 如果只有一个基本类型,可以忽略,但是建议加上
#{}与${}的区别
- #{}可以防止SQL注入
- ${}不能防止SQL注入
9、Lombok
使用步骤:
-
在IDEA中安装Lombok插件:在File——>Settings——>Plugins——>搜索Lombok——>点击
再点击安装即可!
-
在pom.xml中导入Lombok jar 包(父模块/子模块都行)
<!--导入lombok包-->
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
- 在实体类上加注解
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
private String password;
}
@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
@val
@var
@Data 生成的方法有
无参、有参构造,一般联合使用
@NoArgsConstructor
@AllArgsConstructor
10、多对一处理
mybatis-06
- 多个学生对应一个老师
- 对于学生而言,多个学生关联一个老师【多对一】【关联】
- 对于老师而言,一个老师有多个学生【一对多】【集合】
搭建测试环境
- 在pom.xml下导入lombok包
- 新建实体类Teacher和Student
- 建立Mapper接口
- 建立Mapper.xml文件
- 在核心配置文件中绑定注册我们的Mapper接口【用class映射】或Mapper.xml文件【用resource映射】
- 测试查询是否成功
10.1、按照查询嵌套处理【子查询】
<!--
思路:
1.查询所有学生信息
2.根据学生的tid,找到对应的老师
-->
<select id="getStus" resultMap="ST">
select * from mybatis.student;
</select>
<resultMap id="ST" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性需要单独处理-->
<!--association用于处理对象,也就是多对一-->
<!--collection用于处理集合,也就是一对多-->
<association property="teacher" column="tid" javaType="Teacher" select="getTea"/>
</resultMap>
<select id="getTea" resultType="Teacher">
select name from mybatis.teacher;
</select>
10.2、按照结果嵌套处理【联表查询】【推荐使用】
<!--按照结果查询-->
<select id="getStus2" resultMap="ST2">
select s.id sid,s.name sname,t.name tname
from student s,teacher t
where s.tid = t.id;
</select>
<resultMap id="ST2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
11、一对多处理
mybatis-07
一个老师拥有多个学生
环境搭建和多对一一样
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private int tid;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
11.1、按照结果嵌套处理【联表查询】【推荐使用】
<select id="getTeas" resultMap="TS">
select t.id tid,t.name tname,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"/>
<!--javaType 指定属性的类型-->
<!--集合中的泛型用ofType获取-->
<collection property="students" javaType="ArrayList" ofType="Student">
<result property="name" column="sname"/>
</collection>
</resultMap>
11.2、按照查询嵌套处理【子查询】
<select id="getTea2" resultMap="TS2">
select * from mybatis.teacher where id = #{tid};
</select>
<resultMap id="TS2" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" javaType="ArrayList" ofType="Student" select="getStu" column="id"/>
</resultMap>
<select id="getStu" resultType="Student">
select name from mybatis.student where tid = #{tid};
</select>
小结:
- 关联 association 【多对一】
- 集合 collection 【一对多】
- 注意javaType的使用
- 注意ofType的使用
12、动态SQL
什么是动态SQL?
根据不同的条件生成不同的SQL语句
12.1、搭建环境
编写blog表
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
编写实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;//属性和字段 命名不一致
private int views;
}
12.2、where、if
<!--查询数据-->
<select id="getBlogs" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
12.3、choose、when、otherwise
<select id="getBlogChooseWhen" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
author = #{author}
</when>
<otherwise>
views >= #{views}
</otherwise>
</choose>
</where>
</select>
12.4、set
【注意】where不能放在set里面,与SQL语法一样,只能放在后面
<!--更新数据-->
<update id="updateBlogSet" parameterType="map">
update mybatis.blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author},
</if>
</set>
<where>
id = #{id}
</where>
</update>
【小结】
- 所谓的动态SQL,本质还是SQL语句,只是可以在SQL层面,去执行一个逻辑代码
SQL片段:将公共的部分抽取出来,以便复用
-
使用SQL片段抽取公共部分
<sql id="blogDeleteSQL"> delete from mybatis.blog </sql>
-
在需要的地方使用include标签引用
<delete id="deleteBlog" parameterType="map"> <include refid="blogDeleteSQL"/> <where> id = #{id} </where> </delete>
12.5、foreach
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
【foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!
提示 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。】
mybatis-08
-
<!--使用foreach遍历--> <select id="getBlogByForeach" parameterType="map" resultType="blog"> select * from mybatis.blog <where> <foreach collection="ids" item="id" open="(" close=")" separator="or"> id = #{id} </foreach> </where> </select>
-
@Test public void getBlogByForeach(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap<String, Object> map = new HashMap<String, Object>(); ArrayList<Integer> ids = new ArrayList<Integer>(); ids.add(1); map.put("ids",ids); mapper.getBlogByForeach(map); sqlSession.close(); }
13、缓存
13.1、简介
查询 ——>连接数据库 ——>耗资源
一次查询的结果可以暂时存放到一个可以直接读取的地方——>内存:缓存
再次查询相同数据的时候,直接走缓存,不用链接数据库
【什么是缓存?】
- 放在内存中的临时数据
- 可以解决高并发的问题
【为什么使用缓存?】
- 减少和数据库的交互次数,减少系统开销,提高系统效率
【什么样的数据能使用缓存?】
- 经常查询并且不经常改变的数据,可以使用缓存
13.2、mybatis的缓存
- MyBatis包含了一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存,缓存可以极大的提升查询效率
- MyBatis系统默认了两级缓存:一级缓存和二级缓存
- 默认情况下之开启一级缓存,【SqlSession级别的缓存,也称本地缓存】
- 二级缓存需要手动开启和配置,它是基于namespace级别的缓存
- 为了提高扩展性,MyBatis定义了缓存接口Cache,可以通过实现Cache接口实现二级缓存
13.3、一级缓存
【一级缓存也叫本地缓存】
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 如果以后需要获取同样的数据,直接冲缓存中拿,没有必要再去查询数据库
基本上就是这样。这个简单语句的效果如下:
映射语句文件中的所有 select 语句的结果将会被缓存。
映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
缓存不会定时进行刷新(也就是说,没有刷新间隔)。
缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
提示 缓存只作用于 cache 标签所在的映射文件中的语句。如果你混合使用 Java API 和 XML 映射文件,在共用接口中的语句将不会被默认缓存。你需要使用 @CacheNamespaceRef 注解指定缓存作用域。
手动清理缓存
sqlSession.clearCache();
13.4、二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个命名空间对应一个二级缓存
- 工作机制:
- 一个会话查询一条数据,这条数据就会放到当前会话的一级缓存中
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,一级缓存结束,里面的数据放到二级缓存中;
- 新的会话查询数据,可以到二级缓存中去直接获取
- 不同的Mapper查询到的数据会存放到自己的缓存(Map)中
【二级缓存步骤:】
-
在mybatis-config.xml中配置二级缓存
<!--配置缓存--> <setting name="cacheEnabled" value="true"/>
-
在当前Mapper.xml中开启缓存
-
<!--在当前mapper中开启缓存--> <cache/>
-
也可以自定义参数
<!--在当前mapper中开启缓存--> <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
-
【注意】需要将实体类序列化,否则会报错
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private int id;
private String name;
private String pwd;
}
【小结】
- 只要开启二级缓存,在同一个Mapper下就有效
- 所有数据都会先放在一级缓存中
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存中
【数据库查询顺序】
- 先查找二级缓存有没有数据
- 没有数据就查找一级缓存有没有数据
- 一级二级都没有,才会查找数据库
13.5、自定义缓存【Ehcache】
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
【完结】
ion级别的缓存,也称本地缓存】
2. 二级缓存需要手动开启和配置,它是基于namespace级别的缓存
3. 为了提高扩展性,MyBatis定义了缓存接口Cache,可以通过实现Cache接口实现二级缓存
13.3、一级缓存
【一级缓存也叫本地缓存】
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 如果以后需要获取同样的数据,直接冲缓存中拿,没有必要再去查询数据库
基本上就是这样。这个简单语句的效果如下:
映射语句文件中的所有 select 语句的结果将会被缓存。
映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
缓存不会定时进行刷新(也就是说,没有刷新间隔)。
缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
提示 缓存只作用于 cache 标签所在的映射文件中的语句。如果你混合使用 Java API 和 XML 映射文件,在共用接口中的语句将不会被默认缓存。你需要使用 @CacheNamespaceRef 注解指定缓存作用域。
手动清理缓存
sqlSession.clearCache();
13.4、二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个命名空间对应一个二级缓存
- 工作机制:
- 一个会话查询一条数据,这条数据就会放到当前会话的一级缓存中
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,一级缓存结束,里面的数据放到二级缓存中;
- 新的会话查询数据,可以到二级缓存中去直接获取
- 不同的Mapper查询到的数据会存放到自己的缓存(Map)中
【二级缓存步骤:】
-
在mybatis-config.xml中配置二级缓存
<!--配置缓存--> <setting name="cacheEnabled" value="true"/>
-
在当前Mapper.xml中开启缓存
-
<!--在当前mapper中开启缓存--> <cache/>
-
也可以自定义参数
<!--在当前mapper中开启缓存--> <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
-
【注意】需要将实体类序列化,否则会报错
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private int id;
private String name;
private String pwd;
}
【小结】
- 只要开启二级缓存,在同一个Mapper下就有效
- 所有数据都会先放在一级缓存中
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存中
【数据库查询顺序】
- 先查找二级缓存有没有数据
- 没有数据就查找一级缓存有没有数据
- 一级二级都没有,才会查找数据库
13.5、自定义缓存【Ehcache】
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
【完结】