好久没更新博文了,去年备考了一年研究生,然后顺利上岸辽,今年九月份就要读研究生学开发了,以前本科学了一点点数据分析和爬虫的皮毛,希望以后在研究生继续努力学习,研究生阶段主打学习开发,所以自己也是零基础学习,更新下自己学习笔记吧,师从狂神yyds!
一:MyBatis简介
MyBatis是一款优秀的持久层框架,支持sql定制化、存储过程以及高级映射、避免了JDBC的繁琐操作、同时可以使用XML或者注解来进行开发配置操作数据库。
为什么需要使用MyBatis
1.方便
2.JDBC太复杂
3.让数据存入数据库更高效
4.不用MyBatis也可以。更容易上手。
(一):持久化
持久化:将数据在持久状态和瞬时状态进行转化的过程
内存:断点即失
为什么需要持久化?
有一些对象,不能让他丢掉;内存太贵;
(二):持久层
- 完成持久化的代码块
- 层界限十分明显
二:MyBatis入门程序
思路:搭建环境->导入MaBatis->编写代码->测试
(一):搭建数据库
create database `mybatiss`;
use `mybatiss`;
create table `user`(
`id` int(20) not null primary key,
`name` varchar(20) default null,
`pwd` varchar(20) default null
)engine=INNODB default charset=utf8;
insert into `user`(`id`,`name`,`pwd`) VALUES
(11,'狂神aaa','123456'),
(22,'狂神bbb','123356'),
(33,'狂神ccc','124456');
(二):新建项目
1.新建一个普通的maven项目
2.删除src目录
3.导入maven依赖
<!-- 导入依赖-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
(三):创建模块
- 编写mybatis的核心配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- 核心配置文件 -->
<configuration>
<!-- 全局属性设置 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatiss?userSSL=true&userUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
- 编写mybatis工具类
//sqlSessionFactory
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();
}
}
public static SqlSession getSqlSession(){
// SqlSession sqlSession = sqlSessionFactory.openSession();
// return sqlSession;
return sqlSessionFactory.openSession();
}
}
(四):编写代码
- 实体类
package com.kuang.pojo;
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接口
package com.kuang.dao;
import com.kuang.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
- 接口实现类(由原来的UserDaoImpl转换为Mapeer配置文件)
<?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为映射的地址,也就是只有在这个接口中才能使用下边的内容-->
<mapper namespace="com.kuang.dao.UserDao">
<!-- id 外部为调用的名字 resultType 为和数据库表中映射的类名,parameterType就是传递进来的参数id的类型-->
<select id="getUserList" resultType="com.kuang.pojo.User">
select * from mybatiss.user
</select>
</mapper>
(五):测试
注意点:
- org.apache.ibatis.binding.BindingException: Type interface
com.kuang.dao.UserDao is not known to the MapperRegistry.
配置文件更新
<?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"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatiss?userSSL=true&userUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT"/>
<property name="username" value="root"/>
<property name="password" value="200248"/>
</dataSource>
</environment>
</environments>
<!--每一个mapper.xml都需要在mybatis核心配置文件中注册 -->
<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>
</configuration>
测试代码
public class UserDaoTest {
@Test
public void test(){
// 1: 获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// getMapper: 执行SQL
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
// 关闭SqlSession
sqlSession.close();
}
}
maven资源导出依赖
<!--maven的资源过滤问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
二:ResultMap结果集映射
新建一个pojo实体类,属性名和数据库字段不一致
private int id;
private String name;
private String password;
测试出现问题
D:\tech\software\deve\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2023.1.1\lib\idea_rt.jar=57570:C:\Program Files\JetBrains\IntelliJ IDEA 2023.1.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\JetBrains\IntelliJ IDEA 2023.1.1\lib\idea_rt.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2023.1.1\plugins\junit\lib\junit5-rt.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2023.1.1\plugins\junit\lib\junit-rt.jar;D:\tech\大数据\kuang\mabatispro\mabatis-03\target\test-classes;D:\tech\大数据\kuang\mabatispro\mabatis-03\target\classes;D:\tech\software\apache-maven-3.6.1\mvn_resp\com\mysql\mysql-connector-j\8.0.33\mysql-connector-j-8.0.33.jar;D:\tech\software\apache-maven-3.6.1\mvn_resp\com\google\protobuf\protobuf-java\3.21.9\protobuf-java-3.21.9.jar;D:\tech\software\apache-maven-3.6.1\mvn_resp\org\mybatis\mybatis\3.5.5\mybatis-3.5.5.jar;D:\tech\software\apache-maven-3.6.1\mvn_resp\junit\junit\4.12\junit-4.12.jar;D:\tech\software\apache-maven-3.6.1\mvn_resp\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.kuang.dao.UserDaoTest,test
User{id=1, name='狂神1', password='null'}
Process finished with exit code 0
这里是引用
// select * from mybatiss.user where id = #{id}
// select id,name,pwd as password from mybatiss.user where id = #{id}
解决办法
- 起别名
<select id="getUserById" resultType="com.kuang.pojo.User">
select id,name,pwd as password from mybatiss.user where id = #{id}
</select>
(一):ResultMap
结果集映射
数据库: id name pwd
User实体类:id name password
<!-- 结果集映射-->
<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">
select id,name,pwd from mybatiss.user where id = #{id}
</select>
三:分页
为什么要分页?
- 减少数据的处理量
(一):limit分页
语法:select * from user limit startIndex,pageSize
使用Mybatis实现分页,核心SQL
1.接口
// 分页
List<User> getUserBylimit(Map<String,Integer> map);
2.Mapper.xml
<!-- 分页-->
<select id="getUserBylimit" parameterType="map" resultType="user" resultMap="UserMap">
select * from mybatiss.user limit #{startIndex},#{pageSize}
</select>
3.测试
HashMap<String, Integer> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userlist = userDao.getUserBylimit(map);
for (User user1 : userlist) {
System.out.println(user1);
}
(二):RowBounds
接口
List<User> getUserByRowBounds();
mapper
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatiss.user
</select>
测试
// RowBounds实现
RowBounds rowBounds = new RowBounds(1, 2);
//通过java代码层面实现分页
List<User> users = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user1 : users) {
System.out.println(user1);
}
四:使用注解开发
(一):面向接口编程
本质是反射机制实现,底层是动态代理
- 解耦
1.接口
@Select("select * from user")
List<User> getUsers();
2.配置文件绑定接口
<mappers>
<mapper class="com.kuang.dao.UserMapper"/>
</mappers>
3.测试使用
// 注解
List<User> users2 = userDao.getUsers();
for (User user1 : users2) {
System.out.println(user1);
}
四:多对一处理
- 按查询嵌套处理
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<!-- 复杂的属性,单独处理-->
<!-- 对象: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="getStudent2" resultMap="getStudent2">
select s.id sid,s.name sname,t.name tname
from student s,teacher t
where s.tid = t.id;
</select>
<resultMap id="getStudent2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
五:一对多处理
- 按照结果查询
<!-- 按结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname ,t.name tname, t.id tid
from student s, teacher t
where s.tid = t.tid and t.id = #{tid}
</select>
<!-- 集合中的泛型信息使用ofType-->
<resultMap id="TeacherStudent" type="Teacher1">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="student1s" ofType="Student1">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
- 按照查询嵌套处理
<select id="getTeacher1" resultMap="TeacherStudent2">
select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher1">
<collection property="student1s" javaType="ArrayList" ofType="Student1" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from mybatis.student where tid = #{tid}
</select>
六:MyBatis缓存
(一)一级缓存
一级缓存默认是开启的,只在一次SqlSession中有效,也就是连接到关闭期间有用