Mybatis学习笔记
官方文档:https://mybatis.org/mybatis-3/zh/index.html
基于B站狂神视频
mybatis操作流程:
- 创建数据库,创建表
- 搭建环境
<!--导入依赖-->
<dependencies>
<!--mysqlq驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--为了使Mapper.xml文件自动导出-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
- 编写核心配置文件
<?xml version="1.0" encoding="UTF8" ?>
<!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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
</configuration>
-
编写工具类
//sqlSessionFactory --> sqlSession public class MybatisUtils { static SqlSessionFactory sqlSessionFactory = null; 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 命令所需的所有方法。 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
-
实体类
public class User{}
-
接口
public interface UserMapper { public List<User> getUserList(); }
-
接口对应的Mapper配置文件
<?xml version="1.0" encoding="UTF8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace= 绑定一个指定的 Dao/Mapper 接口 --> <mapper namespace="com.sdu.dao.UserMapper"> <!--id 严格对应接口中的方法名--> <select id="getUserList" resultType="com.sdu.pojo.User"> select * from mybatis.user </select> </mapper>
核心配置文件中注册Mapper
<mappers> <mapper resource="com/sdu/dao/UserMapper.xml"/> </mappers>
-
测试
@Test
public void test(){
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();
}
//如果是增删改操作必须提交事务
// sqlSession.commit();
目录结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OnyequlY-1615532503661)(C:\Users\86156\AppData\Roaming\Typora\typora-user-images\image-20210310153241703.png)]
踩坑记录:
Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 6; columnNumber: 17; 1 字节的 UTF-8 序列的字节 1 无效
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-o7eu2Qqd-1615532503663)(C:\Users\86156\AppData\Roaming\Typora\typora-user-images\image-20210302143136910.png)]
原因:Mapper.xml中存在中文注释,并且encoding=UTF-8
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DHjn6TgA-1615532503665)(C:\Users\86156\AppData\Roaming\Typora\typora-user-images\image-20210302143308354.png)]
解决方法:
方法一:删掉中文注释
方法二:更改编码为UTF8
Map的使用:
当数据库中,表、字段、参数过多,可以考虑使用Map!
- UserMapper接口
//用万能Map插入用户
public void addUser(Map<String,Object> map);
- UserMapper.xml
<!--对象中的属性可以直接取出来 传递map的key-->
<insert id="addUser" parameterType="map">
insert into user (id,name,password) values (#{userid},#{username})
</insert>
- 测试
@Test
public void test3(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("userid",4);
map.put("username","旺达幻视");
mapper.addUser(map);
//提交事务
sqlSession.commit();
//关闭资源
sqlSession.close();
}
模糊查询:拼接通配符"%"
mybatis的配置
MyBatis默认的事务管理器就是JDBC ,默认数据源:POOLED
可以通过properties属性实现引用配置文件
<!--引用外部配置文件-->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="root"/>
</properties>
类型别名typeAliases
<!--给实体类起别名-->
<typeAliases>
<typeAlias type="com.sdu.pojo.User" alias="user"></typeAlias>
</typeAliases>
<!--给包起别名-->
<typeAliases>
<package name="com.sdu.pojo"/>
</typeAliases>
映射器 mappers:绑定注册mapper
<!--推荐使用-->
<mappers>
<mapper resource="com/sdu/dao/UserMapper.xml"/>
</mappers>
<!--使用class文件绑定注册,要求接口和对应配置文件必须同名同包-->
<mappers>
<mapper class="com.sdu.dao.UserMapper"/>
</mappers>
<!--使用包扫描,要求接口和对应配置文件必须同名同包-->
<mappers>
<package name="com.kuang.dao"/>
</mappers>
生命周期和作用域
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rNWxmkQ6-1615532503668)(C:\Users\86156\AppData\Roaming\Typora\typora-user-images\image-20210311130109124.png)]
SqlSessionFactoryBuilder:读取核心配置文件,创建SqlSessionFactory
SqlSessionFactory:可以认为是数据库连接池
SqlSession:连接到连接池的一个请求
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-H6kxCZpS-1615532503669)(C:\Users\86156\AppData\Roaming\Typora\typora-user-images\image-20210311130446072.png)]
每个Mapper代表一个业务
结果集映射:解决属性名和字段名的匹配问题
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column数据库中的字段,property实体类中的属性-->
<result column="id" property="id"></result>
<result column="name" property="name"></result>
<result column="pwd" property="password"></result>
</resultMap>
<select id="getUserList" resultMap="UserMap">
select * from USER
</select>
设置日志
<configuration>
<settings>
...
<setting name="logImpl" value="LOG4J"/>
...
</settings>
</configuration>
可选的值有:SLF4J、LOG4J、LOG4J2、JDK_LOGGING、COMMONS_LOGGING、STDOUT_LOGGING、NO_LOGGING
LOG4J:可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
使用LOG4G步骤:
-
导入LOG4J的包
<!--log4j日志--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
-
log4j.properties
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码 log4j.rootLogger=DEBUG,console,file #控制台输出的相关设置 log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%c]-%m%n #文件输出的相关设置 log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/rzp.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.sq1.PreparedStatement=DEBUG
-
配置settings为log4j实现
使用注解开发
步骤:
-
注解在接口上实现
@Select("select * from user") List<User> getUsers(); //方法存在多个参数,所有的参数前面必须加上@Param注解 @Delete("delete from user where id = #{uid}") int deleteUser(@Param("uid") int id); //关于@Param()注解,基本数据类型和String类型需要添加,引用类型不需要 //#{}对应于预编译sql,${}对应于拼接
-
核心配置文件中绑定接口
<mappers>
<mapper class="com.sdu.dao.UserMapper"/>
</mappers>
Mybatis执行流程
Lombok
Lombok项目是一个Java库,它会自动插入编辑器和构建工具中,Lombok提供了一组有用的注释,用来消除Java类中的大量样板代码。仅五个字符(@Data)就可以替换数百行代码从而产生干净,简洁且易于维护的Java类。
使用步骤:
-
在IDEA中安装Lombok插件
-
在项目中导入lombok的jar包
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> <scope>provided</scope> </dependency>
-
在程序上加注解
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private String password; }
多对一查询
按照查询嵌套处理
<!-- 思路: 1. 查询所有的学生信息 2. 根据查询出来的学生的tid寻找特定的老师 (子查询) --> <select id="getStudent" resultMap="StudentTeacher"> select * from student </select> <resultMap id="StudentTeacher" type="student"> <result property="id" column="id"/> <result property="name" column="name"/> <!--复杂的属性,我们需要单独出来 对象:association 集合:collection--> <collection property="teacher" column="tid" javaType="teacher" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="teacher"> select * from teacher where id = #{id} </select>
按照结果嵌套处理
<!--按照结果进行查询-->
<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"></result>
</association>
</resultMap>
MyBatis缓存
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存,默认情况下,只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存),二级缓存需要手动开启和配置,他是基于namespace级别的缓存。为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。
er2" type=“student”>
## MyBatis缓存
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存,默认情况下,只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存),二级缓存需要手动开启和配置,他是基于namespace级别的缓存。为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。
![img](https://img-blog.csdnimg.cn/20200623165404113.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0RERERlbmdf,size_16,color_FFFFFF,t_70#pic_center)