简介
什么是MyBatis
mybatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。MyBatis可以使用简单的XML或注解来配置和映射原生类型、接口和Java的POJO(Plain Old Java Object,普通老式Java对象)为数据库中的记录。
持久化
数据持久化
持久化就是将程序的数据在持久状态和瞬时状态转化的过程
持久层
完成持久化工作的代码块
为什么需要MyBatis
mybatis框架帮助程序员轻松的与数据库进行交互
优点:
简单易学
灵活
sql和代码分离,提高了可维护性
提供映射标签,支持对象与数据库的orm字段关系映射
提供对象关系映射标签,支持对象关系组件维护
提供xml标签,支持编写动态sql
最重要的一点:使用的人多
Spring SpringMVC SpringBoot
第一个MyBatis程序
搭建环境,编写测试代码,测试
创建数据库
CREATE DATABASE 'mybatis';
USE 'mybatis';
CREATE TABLE 'user'(
id INT(20) NOT NULL PRIMARY KEY,
name VARCHAR(30) DEFAULT NULL,
pwd VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf-8;
INSERT INTO 'user'('id','name','pwd') VALUES(1,'kuangshen','123'),(2,'zhangsan','123'),(3,'lisi','456')
新建maven项目,pom文件添加依赖
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
编写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>
<!--引入外部配置文件-->
<properties resource="db.properties"/>
<settings>
<!--标准日志工厂实现-->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!--是否开启自动驼峰命名规则映射-->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<environments default="development">
<environment id="development">
<!--使用jdbc事务管理 -->
<transactionManager type="JDBC"/>
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<!-- 引入映射配置文件 -->
<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>
</configuration>
编写mybatis工具类
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
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完全包含了面向数据库执行sql命令所需的所有方法
*
* @return
*/
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
编写代码
实体类
@Data
public class User {
private int id;
private String name;
private String pwd;
}
Dao接口
public interface UserDao {
List<User> getUserList();
}
Dao接口实现类由原来的UserDaoImpl转换为一个Mapper.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:命名空间,用于绑定接口
id:唯一标识
resultType:返回值类型
-->
<mapper namespace="com.kuang.dao.UserDao">
<!-- select查询语句 -->
<select id="getUserList" resultType="com.kuang.pojo.User">
select * from user
</select>
</mapper>
测试代码
public class UserDaoTest{
@Test
public void test(){
// 获取sqlsession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 方式一:getMapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
// 方法二:
List<User> userList = sqlSession.selectList("com.kuang.UserDao.getUserList");
for(User user : userList ){
System.out.println(user);
}
// 关闭sqlsession
sqlSession.close();
}
}
此处要添加maven资源过滤
CRUD
1.namespace
namespace中的包名要和Dao/mapper接口的包名一致
2.select
选择、查询语句
id:就是对应的namespace中的方法名
resultType:Sql语句的返回值
parameterType:参数类型
1.编写接口
2.编写mapper.xml中的sql语句
3.测试
代码示例
接口
public interface UserMapper {
// 查询全部用户
public List<User> getUserList();
// 根据ID查询用户
public User getUserById(int id);
// insert一个用户
public int addUser(User user);
// 修改用户
public void updateUser(User user);
// 删除一个用户
public int deleteUser(int id);
}
mapper.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:命名空间,用于绑定接口
id:唯一标识
resultType:返回值类型
-->
<mapper namespace="com.kuang.dao.UserMapper">
<!-- select查询语句 -->
<select id="getUserList" resultType="com.kuang.pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" parameterType="int" resultSetType="com.kuang.pojo.User">
select * from mybatis.user where id = #{id}
</select>
<!-- 对象中的属性可以直接取出来 -->
<insert id="addUser" parameterType="com.kuang.dao.User" resultSetType="int">
insert into mybatis.user(id,name,pwd) VALUES (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="com.kuang.dao.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 UserMapperTest {
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user.toString());
sqlSession.close();
}
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.addUser(new User(2,"zhangsan","12345"));
if(res>0){
System.out.println("插入成功");
}
// 提交事务(增删改)
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(2,"lubu","2222");
mapper.updateUser(user);
// 提交事务(增删改)
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(2);
// 提交事务(增删改)
sqlSession.commit();
sqlSession.close();
}
}
注意点:
- 增删改需要提交事务
万能Map和模糊查询
Map
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map
接口
public interface UserMapper {
// 万能map
public User addUser(Map<String,Object> map);
}
mapper.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:命名空间,用于绑定接口
id:唯一标识
resultType:返回值类型
-->
<mapper namespace="com.kuang.dao.UserMapper">
<!--
传递map中的key
-->
<select id="addUser" parameterType="map">
insert into mybatis.user (id,name,pwd) values (#{userid},#{userName},#{passWord})
</select>
</mapper>
测试
public class UserMapperTest {
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map = new HashMap<String,Object>();
map.put("userid",5);
map.put("userName","hello");
map.put("passWord","666");
mapper.addUser(map);
// 提交事务(增删改)
sqlSession.commit();
sqlSession.close();
}
}
Map传递参数,直接在sql中取出key即可
对象传递参数,直接在sql中取对象的属性即可
只有一个基本类型参数的情况下,可以直接在sql中取到
多个参数用map,或者注解
模糊查询
模糊查询怎么写
1.java代码执行的时候,传递通配符%%
List<User> userList = mapper.getUserList("%李%");
2.在sql拼接中使用通配符
select * from mybatis.user where name like "%"#{value}"%"
配置解析
核心配置文件
- 官方建议使用mybatis-config.xml
- MyBatis的配置文件包含了会深深影响MyBatis行为的设置和属性信息
- configuration 配置
- properties 属性
- setting 设置
- typeAliases 类型别名
- typeHandlers 类型处理器
- objectFactory 对象工厂
- plugins 插件
- environments 环境配置,这个标签下可以配置多个环境
- environment 环境配置
- transactionManager 事务管理器
- dataSource 数据源
- databaseIdProvider 数据库厂商标识
- mappers 映射器
环境配置(environment )
MyBatis可以配置成适应多种环境
尽管可以配置多个环境,但每个sqlSessionFactory实例只能选择一种环境
学会使用配置多套运行环境
MyBatis默认的事务管理器就是JDBC,连接池POOLED
属性(properties)
我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的java属性文件中配置,也可以通过properties元素的子元素来传递(db.properties)
编写一个数据库配置文件
driver=com.mysql.jdbc.driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123
在核心配置文件中引入
<!-- 引入外部配置文件 -->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="pwd" value="11111"/>
</properties>
可以直接引入外部文件
可以在其中增加一些属性配置
如果两个文件由同一个字段,优先使用外部配置文件的
类型别名(typeAliases)
类型别名是为Java类型设置一个短的名字
存在的意义仅在于用来减少类完全限定名的冗余
<!--可以给实体类起别名-->
<typeAliases>
<typeAlias type="com.kuang.pojo.User" alias="User"/>
</typeAliases>
也可以指定一个包名,MyBatis会在包名下面搜索需要的Java Bean,比如:扫描实体类的包,它的默认别名就为这个类的类名,首字母小写
<!--可以给实体类起别名-->
<typeAliases>
<package name="com.kuang.pojo"/>
</typeAliases>
在实体类比较少的时候,使用第一种
如果实体类多,建议使用第二种
第一种可以DIY别名,第二种则不可以,如果非要改,需要在实体类上增加注解
@Alias("people")
public class User{
}
其他配置
setting
typeHandlers
objectFactory
plugins
mybatis-generator-core
mybatis-plus
通用mapper
映射器(mapper)
MapperRegistry:注册绑定我们的Mapper文件
方式一:resource
<!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册-->
<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>
方式二:class
<!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册-->
<mappers>
<mapper class="com/kuang/dao/UserMapper"/>
</mappers>
注意点:
接口和他的Mapper配置文件必须同名
接口和他的Mapper配置文件必须在同一个包下
方式三:使用扫描包进行注入绑定
<!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册-->
<mappers>
<package name="com.kuang.dao"/>
</mappers>
注意点:
接口和他的Mapper配置文件必须同名
接口和他的Mapper配置文件必须在同一个包下
生命周期和作用域
生命周期和作用域,是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder
一旦创建了SqlSessionFactory,就不再需要SqlSessionFactoryBuilder了
SqlSessionFactory
说白了就是可以想象为:数据库连接池
SqlSessionFactory一旦被创建就应该在应用的运行期间存在一直,没有任何理由丢弃它或重新创建实例
因此SqlSessionFactory的最佳作用域是应用作用域
最简单的就是使用单例模式或者静态单例模式
SqlSession
连接到连接池的一个请求
SqlSession的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
用完之后需要关闭,否则资源被占用
解决属性名和字段名不一致的问题
举例:
数据库中的字段叫pwd
类中的属性叫password
解决方法:
起别名
<select id="getUserById" resultType="com.kuang.pojo.User">
select id,name,pwd as password from mybatis.user where id = #{id}
</select>
resultMap
<!--结果集映射-->
<resultMap id="resultMap" type="User">
<!--column数据库中的字段,property实体类中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" resultType="resultMap">
select * from mybatis.user where id = #{id}
</select>
resultMap元素是MyBatis中最重要最强大的元素
ResultMap的设计思想是,对于简单的语句根本不需要配置显示的结果映射,而对于复杂一点的语句只需要描述他们呢的关系就行了
ResultMap最优秀的敌方在于,虽然你已经对它相当了解了,但是根本就不需要显示地用到他们
日志
如果一个数据库操作,出现了异常,我们需要排错,日志是最好的助手
日志工厂
在MyBatis中具体使用哪一个日志实现,在设置中设定
STDOUT_LOGGING标准日志输出
<settings>
<!--标准的日志工厂-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
Log4j
什么是log4j
- Log4j是apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 我们也可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致的控制日志的生成过程
- 通过一个配置文件来灵活的进行
1.先导入log4j的包
<dependency>
<groupId>log4j</groupId>
<artifacId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2.添加log4j的配置文件
3.在mybatis-config.xml中配置
<settings>
<!--标准的日志工厂-->
<setting name="logImpl" value="LOG4J"/>
</settings>
简单使用
1.在要使用log4j的类中,导入包import org.apache.log4j.Logger;
2.日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
3.日志级别
info
debug
error
分页
为什么要分页
减少数据的处理量
分页方式一(推荐)
使用limit分页
slect * from table limit startindex,pagesize;
使用MyBatis实现分页,核心SQL
1.接口
2.Mapper.xml
3.测试
接口
public List<User> getUserByLimit(Map<String,Integer> map);
mapper.xml
<!--分页-->
<select id="getUserByLimit" parameterType="map" resultType="user">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
测试
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userList = mapper.getUserByLimit(map);
sqlSession.close();
}
分页方式二(不推荐)
不再使用sql来实现分页,使用java代码实现
接口
public void getUserByRowBounds(Map<String,Integer> map);
Mapper.xml
<!--分页-->
<select id="getUserByRowBounds" resultType="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
测试
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//RowBounds实现
RowBounds rowBounds = new RowBounds(1,2);
//通过Java代码层面实现分页
List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for(User user : userList){
System.out.println(user);
}
sqlSession.close();
}
分页插件
PageHelper 分页 神器
引入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
xml
<select id="page" resultType="com.hyt.cases.dto.CaseDto" >
select *from accms_case
</select>
mapper
List<CaseDto> page();
使用pagehelper
// controller
// pageNum:当前页数
// pageSize:条数
// userInfoPage:所有数据,分页数据和总条数等
public PageInfo<CaseDto> page(@RequestParam(required =false)Integer pageNum,
@RequestParam(required =false)Integer pageSize){
PageHelper.startPage(pageNum,pageSize);
List<CaseDto> list=applicantlnMapper.page();
PageInfo<CaseDto> userInfoPage = new PageInfo<CaseDto>(list);
return userInfoPage;
}
使用注解开发
面向接口编程
使用面向接口编程的根本原因:解耦,可扩展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好
在一个面向对象的系统中,系统的各种功能是有许许多多不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了
而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程
关于接口的理解
接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离
接口的本身反映了系统设计人员对系统的抽象理解
接口应有两类:
第一类是对一个个体的抽象,它可对应为一个抽象体
第二类是对一个个体某一方面的抽象,即形成一个 抽象面
一个个体可能有多个抽象面,抽象提与抽象面是有区别的
三个面相区别
面向对象是指,我们考虑问题时,以对象为单位,考虑他的属性及方法
面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑他的实现
接口设计与非接口设计是针对服用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构
使用注解开发
声明接口
public interface UserMapper{
@select("select * from user")
public List<User> getUsers();
}
mybatis-config.xml中绑定接口
<!--绑定接口-->
<mapper>
<mapper class="com.kuang.dao.UserMapper"/>
</mapper>
测试代码
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 底层主要应用反射
UserMapper userMapper = sqlsession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
System.out.println(users)
sqlSession.close();
}
本质:反射机制实现
底层:动态代理
分析MyBatis的执行流程
- Resources获取加载全局配置文件
- 实例化SqlSessionFactoryBuilder构造器
- 解析全局配置文件文件流XMLConfigBuilder
- Configuration所有的配置信息
- SqlSessionFactory实例化
- transactional事务管理
- 创建exector执行器
- 创建SqlSession
- 实现CRUD
- 提交事务
- 关闭SqlSession
使用注解完成CRUD
我们可以在工具类创建的时候实现自动的事务管理
sqlSessionFactory.openSession(true);
Mapper接口,增加注解
public interface UserMapper{
@Select("select * from user")
List<User> getUsers();
// 方法存在多个参数,所有的参数前面必须加上@Param(“id”)注解
@Select("select * from user where id = #{Aid}")
User getUserById(@Param("Aid")int id);
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
int addUser(User user);
@Update("update user set name=#{name},pwd=#{password} where id = #{id}")
int updateUser(User user);
@Delete("delete from user where id = #{uid}")
int deleteUser(@Param("uid")int id);
}
注意:
必须将接口注册绑定到全局配置文件中
@Param注解
基本类型的参数或者String类型,需要加上
引用类型不需要加
如果只有一个基本类型的话,可以忽略,但是建议加上
我们在sql中引用的就是@Param中设定的属性名
#{}和${}
多数使用#{},可以防止sql注入(对sql语句进行预编译)
${}无法防止sql注入
Lombok
使用步骤:
1.在IDEA中安装Lombok插件
2.在项目中导入Lombok的jar包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
@Data:无参构造,get,set,tostring,hashcode,equals
@AllArgsConstructor:有参构造
@NoAllArgsConstructor:无参构造
@ToString:
@Getter
@Setter
多对一处理
@Data
public class Teacher{
private int id;
private String name;
}
@Data
public class Student{
private int id;
private String name;
// 一个学生关联一个老师
private Teacher teacher;
}
public interface StudentMapper{
// 查询所有的学生信息,以及对应的老师的信息
public List<Student> getStrudent();
}
public interface TeacherMapper{
@Select("select * from teacher where id = #{uid}")
Teacher getTeacher(@Param("uid")int id);
}
编写对应的mapper
<mapper namespace="com.kuang.dao.StudentMapper">
<!--第一种思路:
按照结果嵌套处理
-->
<select id="getStudent2" resultType="">
select s.id sid,s.anme sname,t.name tname from student s,teacher t where s.tid = t.id;
</select>
<resultMap id="StudentTeacher2" type="Strudent">
<!-- 主键使用<id>标签,普通字段使用<result>标签 -->
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher"/>
<result property="name" column="tname"/>
</association>
</resultMap>
<!--第二种思路:
1.查询所有的学生信息
2.根据查询出来的学生的tid,寻找对应的老师 子查询
-->
<select id="getStudent" resultType="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id">
<result property="name" column="name">
<!--复杂属性,我们需要单独处理 对象:association 集合:collection-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher">
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{id}
</select>
<select id="getStudent" resultType="Student">
select s.id,s.name,t.name from student s,teacher t where s.tid = t.id;
</select>
</mapper>
测试类
@Test
public void teacherTest{
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> student = mapper.getStudent();
for(Student s : student){
System.out.println(s);
}
sqlSession.close();
}
回顾Mysql多对一查询方式:
1.子查询
2.联表查询
一对多处理
@Data
public class Teacher{
private int id;
private String name;
// 一个老师拥有多个学生
private List<Student> students;
}
@Data
public class Student{
private int id;
private String name;
}
public interface StudentMapper{
// 获取老师
List<Teacher> getTeachers();
// 获取指定的老师和所有的学生
Teacher getTeacher(@Param("tid")int id);
}
Mapper.xml
<!-- StudentMapper.xml -->
<mapper namespace="com.kuang.dao.StudentMapper">
<select id="getTeachers" resultType="Teacher">
select * from teacher;
</select>
</mapper>
<!-- TeacherMapper.xml -->
<mapper namespace="com.kuang.dao.TeacherMapper">
<!--按结果嵌套查询(推荐)-->
<select id="getTeachers" 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>
<!--子查询-->
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname">
<!--
复杂的属性,我们需要单独处理
对象:association
集合:collection
javaType指定属性的类型
集合中的泛型信息,我们使用ofType获取
-->
<collection property="students" javaType="Student"/>
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
<!--多个嵌套方式-->
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid = #{tid}
</select>
</resultMap>
</mapper>
测试方法
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(s);
sqlSession.close();
}
总结
1.关联 - association【多对一】
2.集合 - collection【一对多】
3.javaType & ofType
1.javaType 用来指定实体类中属性的类型
2.ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
注意点:
1.保证SQL的可读性,尽量保证通俗易懂
2.注意一对多和多对一中,属性名的字段的问题
3.如果问题不好排查错误,可以使用日志,建议使用Log4j
resultMap标签讲解:
:
用来标识出对象的唯一性,比如用表的主键
column属性:指定数据库对应的字段名
property属性:指定的javaBean的字段名
jdbcType属性:数据库类型
javaType属性:属性的java类型
typeHandler属性:数据库与Java类型匹配处理器
:
非主键的映射规则
:
property:同标签
javaType:同标签
select:指定嵌套SQL,可以是本XML或者其他XML文件中的
fetchType:延迟加载,lazy打开延迟加载;eager积极加载
column:同标签
resultMap:不使用嵌套SQL,而是使用复杂SQL一次取出关联的对象,并封装
resultSet:引用根据标签得到的resultSets
autoMapping:同标签
columnPrefix:关联多张表查询时,为了使列明不重复,使用此功能可以减少开发量
foreignColumn:外键列
notNullColumn:不为空的列,如果指定了列,那么只有当字段不为空时,Mybatis才会真正创建对象,才能得到我们想要的值
typeHandler:同标签
:
和association很像,collection是负责处理多行的结果集
:
负责根据返回的字段的值封装不同的类型
动态SQL
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
利用动态SQL这一特性可以彻底摆脱这种痛苦
动态SQL元素和JSTL或基于类似XML的文本处理器相似。在MyBatis之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需要学习原来一般的元素便可。MyBatis采用功能强大的基于OGNL的表达式来淘汰其他大部分元素
if
choose(when,otherwise)
trim(where,set)
foreach
搭建环境
准备数据库
CREATE TABLE 'blog'(
'id' varcher(50) NOT NULL COMMENT '博客id',
'title' vachar(100) NOT NULL COMMENT '博客标题',
'author' vachar(30) NOT NULL COMMENT '博客作者',
'create_time' datetime NOT NULL COMMENT '创建时间',
'author' int(30) NOT NULL COMMENT '浏览量'
)ENGINE=InnoDB DEFAULT CHARSER=utf8
准备实体类
@Data
public class Blog{
private String id;
private String title;
private String author;
private Date createTime;//属性名和字段名不一致
private int views;
}
BlogMapper接口
public interface BlogMapper{
// 插入数据
int addBook(Blog blog);
// 查询博客
List<Blog> queryBlogIF(Map map);
// 查询
List<Blog> queryBlogChoose(Map map);
// 更新博客
int updateBlog(Map map);
}
BlogMapper.xml
<mapper namespace="com.kuang.dao.BlogMapper">
<insert id="addBook" parameterType="blog">
insert into blog(id,title,author,create_time,views)
values(#{id},#{title},#{author},#{create_time},#{views})
</insert>
<select id="queryBlogIF" parameterType="map">
select * from blog where 1=1;
<if test="title != null">
and title = #{title}
</if>
</select>
<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>
<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>
</mapper>
测试类
@Test
public void queryBlogIF(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap<>();
map.put("title","JAVA");
List<Blog> blogs = mapper.queryBlogIF(map);
for(Blog blog : blogs){
System.out.println(blog);
}
sqlSession.close();
}
if
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
select * from user where
<if test="username != null">
username=#{username}
</if>
<if test="username != null">
and sex=#{sex}
</if>
</select>
where
如果拼接的sql语句开头是and或者是or,where标签会自动将其清理掉
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
select * from user
<where>
<if test="username != null">
username=#{username}
</if>
<if test="username != null">
and sex=#{sex}
</if>
</where>
</select>
set
如果只能拼接上一个条件,那么set标签可以将sql语句结尾的逗号删除掉
<!-- 根据 id 更新 user 表的数据 -->
<update id="updateUserById" parameterType="com.ys.po.User">
update user u
<set>
<if test="username != null and username != ''">
u.username = #{username},
</if>
<if test="sex != null and sex != ''">
u.sex = #{sex}
</if>
</set>
where id=#{id}
</update>
choose
语法类似于java中的switch case
<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>
trim
trim标记是一个格式化的标记,可以完成set或者是where标记的功能
①、用 trim 改写上面第二点的 if+where 语句
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
select * from user
<!-- <where>
<if test="username != null">
username=#{username}
</if>
<if test="username != null">
and sex=#{sex}
</if>
</where> -->
<trim prefix="where" prefixOverrides="and | or">
<if test="username != null">
and username=#{username}
</if>
<if test="sex != null">
and sex=#{sex}
</if>
</trim>
</select>
prefix:前缀
prefixoverride:去掉第一个and或者是or
②、用 trim 改写上面第三点的 if+set 语句
<!-- 根据 id 更新 user 表的数据 -->
<update id="updateUserById" parameterType="com.ys.po.User">
update user u
<!-- <set>
<if test="username != null and username != ''">
u.username = #{username},
</if>
<if test="sex != null and sex != ''">
u.sex = #{sex}
</if>
</set> -->
<trim prefix="set" suffixOverrides=",">
<if test="username != null and username != ''">
u.username = #{username},
</if>
<if test="sex != null and sex != ''">
u.sex = #{sex},
</if>
</trim>
where id=#{id}
</update>
suffix:后缀
suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)
SQL片段
有的时候,我们可能会将一些功能的部分抽取出来,方便复用
1.使用SQL标签抽取公共的部分
<sql id="if-title-author">
<if test="title!=null">
title = #{title},
</if>
<if test="author!=null">
author= #{author}
</if>
</sql>
2.在需要使用的地方使用Include标签引用即可
<select id="queryBlogIF" parameterType="map">
select * from blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
注意事项:
1.最好基于单表来定义SQL片段
2.不要存在where标签
foreach
<select>
select * from blog
<where>
<foreach item="id" index="index" collection="ids" open="(" separator="," close=")">
#{id}
</foreach>
</where>
</select>
sql:(id=1 or id=2 or=3)
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
先在mysql中调试完整的SQL,再去实现动态SQL
缓存
介绍
1.什么是缓存
存在内存中的临时数据
将用户经常查询的数据放在缓存中,用户去查询数据就不用从磁盘(关系型数据库数据文件)上查询,从而提高查询效率,解决了高并发系统的性能问题
2.为什么使用缓存
减少和数据库的交互次数,减少系统开销,提高系统效率
3.什么样的数据能使用缓存
经常查询并且不经常改变的数据
MyBatis缓存
MyBatis包含一个非常强大的查询缓存特性,它可以非常方便的制定和配置缓存,缓存可以极大的提升查询效率
MyBatis系统中默认定义了两个级别缓存:一级缓存和二级缓存
默认情况下,只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
二级缓存需要手动开启和配置,他是基于namespace级别的缓存
为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
一级缓存(SqlSession级别的缓存)
一级缓存也叫本地缓存
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
二级缓存(namespace级别的缓存)
二级缓存也叫全局缓存,一级缓存作用域太低,所以诞生了二级缓存
基于namespace级别的缓存,一个名称空间,对应一个二级缓存
工作机制:
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
- 如果当前会话关闭了,这个会话对应的一级缓存就没了,但是我们想要的是,会话关闭了,一级缓存中的数据被保存到了二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己对应的缓存中
步骤:
1.开启全局缓存
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
2.在mapper中开启二级缓存
<cache
evication="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
3.实体类需要序列化,否则会报错
总结:
只要开启了二级缓存,在同一个mapper下就有效
所有的数据都会先放在一级缓存
只有当会话提交或者关闭的时候才会放在二级缓存中
缓存原理
自定义缓存Ehcache
Ehcache是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider
要在程序中使用ehcache,先导包
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
可以在resource引入ehcache.xml的配置文件,可以自定义一些配置,例如:缓存最大数,硬盘最大缓存数等等
在mapper中启用ehcache
<?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">
<mapper namespace="com.kuang.dao.UserDao">
<!--启用ehcache作为耳机缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<!-- select查询语句 -->
<select id="getUserList" resultType="com.kuang.pojo.User">
select * from user
</select>
</mapper>
自定义缓存需要实现cache接口
public class MyCache implements Cache{
public String getId(){
return null;
}
public void putObject(Object o,Object o1){
}
public Object getObject(Object o){
return null;
}
public Object removeObject(Object o){
return null;
}
public void clear(){
}
public int getSize(){
return 0;
}
}
狂神说 MyBatis教程 上课笔记: