环境:
- jdk1.8
- mysql5.7
- maven3.6.1
- idea
回顾:
- jdbc
- mysql
- java基础
- maven
- junit
SMM框架 好的学习方式:看官方文档
1、简介 1.1、什么是MyBatis- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- MyBatis本是apache的一个开源项目iBatis,2010年这个项目且改名为MyBatis。
- 2013年11月迁移到Github。
如何获得Mybatis
-
maven仓库
org.mybatis mybatis 3.5.7 -
github:https://github.com/mybatis/mybatis-3/releases
-
中文文档:https://mybatis.org/mybatis-3/zh/index.html
数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 内存:断电即失
- 数据库(jdbc),io文件持久化
- 生活:罐头
为什么需要持久化?
- 有一些对象,不能让它丢失
- 内存太贵
dao层 server层 controller层
- 完成持久化工作的代码块
- 层界限十分明显
- 帮忙程序员将数据存入到数据库中
- 方便
- 传统的jdbc太复杂了。简化。框架。自动化。
- 不用mybatis也可以。容易上手。技术没有高低之分
- 优点:
- 简单易学
- 灵活
- sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql
- 最重要的一点:使用的人多!
思路:搭建环境–》导入Mybatis–》编写代码–》测试
2.1、搭建环境搭建数据库
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=utf8; INSERT INTO `user`(`id`,`name`,`pwd`) VALUES (1,'zyy','123456'), (2,'张三','123456'), (3,'李四','123456');
新建项目
-
新建一个普通的maven项目
-
删除src目录(作为父工程)
-
导入maven依赖
mysql mysql-connector-java 5.1.47 org.mybatis mybatis 3.5.7 junit junit 4.12
-
编写mybatis的核心配置文件
-
编写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 { String resource = "mybatis-config.xml"; try { InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(); } }
-
实体类
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接口
```java
import com.zyy.pojo.User;
import java.util.List;
public interface UserDao {
List getUserList();
}
-
接口实现类(由原来的UserDaoImpl转为一个Mapper配置文件)
select id, name, pwd from `user`
注意点:
org.apache.ibatis.binding.BindingException: Type interface com.zyy.dao.UserDao is not known to the MapperRegistry.
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aSYZU5OE-1654251533295)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220312095816822.png)]
Caused by: java.io.IOException: Could not find resource com/zyy/dao/UserMapper.xml
pom改成:
maven-study com.zyy 1.0-SNAPSHOT 4.0.0 mybatis-01 src/main/resources ***.xml false src/main/java ***.xml false org.apache.maven.plugins maven-compiler-plugin 3.10.0 1.8 1.8
MapperRegistry是什么?
核心配置文件中注册mappers
-
junit测试
import com.zyy.pojo.User; import com.zyy.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserDaoTest { @Test public void getUserList() { SqlSession sqlSession = null; try { sqlSession = MybatisUtils.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); ListuserList = userDao.getUserList(); userList.forEach(user -> System.out.println(user.toString())); } finally { if (sqlSession != null) { sqlSession.close(); } } } }
可能会遇到的问题
- 配置文件没有注册
- 绑定接口错误
- 方法名不对
- 返回类型不对
- Maven导出资源问题
增加(Create)、检索(Retrieve)、更新(Update)和删除(Delete)
1、namespacenamespace中的包名要和dao/mapper接口的包名一致
2、select选择,查询语句:
- id :就是对应的namespace中的方法
- resultType:sql语句执行的返回值
- parameterType:参数类型
-
编写接口
User getUserById(int id);
-
编写接口对应的mapper中的语句
-
测试
@Test public void getUserById() { SqlSession sqlSession = null; try { sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.getUserById(1); System.out.println(user.toString()); } finally { if (sqlSession != null) { sqlSession.close(); } } }
-
编写接口
int addUser(User user);
-
编写接口对应的mapper中的语句
insert into `user`(id, name, pwd) values (#{id},#{name},#{pwd}) -
测试
@Test public void addUser() { SqlSession sqlSession = null; try { sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int num = userMapper.addUser(new User(4, "哈哈", "123456")); if (num > 0) { System.out.println("插入成功"); } //提交事务 sqlSession.commit(); } finally { if (sqlSession != null) { sqlSession.close(); } } }
-
编写接口
int updateUser(User user);
-
编写接口对应的mapper中的语句
update `user` set name=#{name},pwd=#{pwd} where id = #{id} -
测试
@Test public void updateUser() { SqlSession sqlSession = null; try { sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int num = userMapper.updateUser(new User(4, "呵呵", "123456")); if (num > 0) { System.out.println("修改成功"); } //提交事务 sqlSession.commit(); } finally { if (sqlSession != null) { sqlSession.close(); } } }
-
编写接口
int deleteUser(int id);
-
编写接口对应的mapper中的语句
delete from `user` where id = #{id} -
测试
@Test public void deleteUser() { SqlSession sqlSession = null; try { sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int num = userMapper.deleteUser(4); if (num > 0) { System.out.println("删除成功"); } //提交事务 sqlSession.commit(); } finally { if (sqlSession != null) { sqlSession.close(); } } }
注意点:增删改需要提交事务才会生效
6、分析错误- 标签不要匹配错!
- resource绑定mapper,需要使用路径!
- 程序配置文件必须符合规范!
- NullPointerException,没有注册到资源!
- 输出的xml文件中存在中文乱码问题!
- maven资源没有导出问题!
假设,我们的实例类,或者数据库中的表,字段或者参数过多,我们应该考虑使用map!
接口
int addUser2(Mapmap);
mapper
insert into `user`(id, name, pwd) values (#{userId},#{userName},#{password})
测试
@Test
public void addUser2() {
SqlSession sqlSession = null;
try {
Map map = new HashMap<>();
map.put("userId", 5);
map.put("userName", "zyy");
map.put("password", "123456");
sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int num = userMapper.addUser2(map);
if (num > 0) {
System.out.println("插入成功!");
}
sqlSession.commit();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
Map传递参数,直接在sql中取出key即可!
对象传递参数,直接在sql中取对象的属性即可!
只有一个基本类型的情况下,可以直接在sql中取到!
多个参数用Map,或者注解!
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cx5B8Pza-1654251533296)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220312184129486.png)]
8、思考题模糊查询怎么写?
-
java代码执行的时候,传递通配符%
List
userList = userMapper.getUserLike("%z%"); -
在sql中拼接使用通配符 (不推荐,容易引起sql注入问题)
select id, name, pwd from `user` where name like "%"#{value}"%"
-
mybatis-config.xml
-
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uvLAcCZA-1654251533297)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220312214122775.png)]
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
学会使用配置多套运行环境!
MyBatis默认的事务管理器就是jdbc,连接池:POOLED
3、属性(properties)我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties】
在xml中,所有的标签都可以规定其顺序
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M8gzz944-1654251533298)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220312220720720.png)]
编写一个配置文件
db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8 username=root password=123456
在核心配置文件中引入
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
- 如果两个文件有同一个字段,优先使用外部配置文件的!
- 类型别名可为 Java 类型设置一个缩写名字。
- 意在降低冗余的全限定类名书写。
核心配置文件
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
扫描实体类的包,它的默认别名就是这个类的类名,首字母小写。
在实体类比较少的时候,使用第一种方式。
如果实体类比较多,建议使用第二种。
第一种可以DIY别名,第二种不行,如果非要改的话,需要在实体上增加注解
@Alias("user")
public class User {}
5、设置(settings)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pFzxVzm5-1654251533299)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220312223626908.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0G85OceQ-1654251533300)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220312223637156.png)]
6、其他配置- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- mybatis-generator-core
- mybatis-plus
- 通用mapper
MapperRegistry:注册绑定我们的mapper文件
方式一:
方式二:使用class文件绑定注册
注意点:
- 接口和它的Mapper配置文件必须同名!
- 接口和它的Mapper配置文件必须在同一个包下!
方式三:使用扫描包进行注入绑定
注意点:
- 接口和它的Mapper配置文件必须同名!
- 接口和它的Mapper配置文件必须在同一个包下!
练习时间:
- 将数据库配置文件外部引入
- 实体类别名
- 保证UserMapper接口和UserMapper.xml改成一致!并且放到同一个包下!
生命周期和作用域类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder- 一旦创建了 SqlSessionFactory,就不再需要它了
- 局部变量
- 说白了就是可以想象为:数据库连接池
- 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
- SqlSessionFactory 的最佳作用域是应用作用域
- 最简单的就是使用单例模式或者静态单例模式。
- 连接到连接池的一个请求
- 每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 用完之后需要赶紧关闭,否则资源被占用!
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jxCnqaGK-1654251533301)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220326092431602.png)]
这里的每一个mapper,就代表一个具体的业务!
5、解决属性名和字段名不一致的问题 1、问题数据库中字段
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bCshHagl-1654251533302)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220326094813973.png)]
新建一个项目,拷贝之前的,测试实体类字段不一致的情况
public class User {
private int id;
private String name;
private String password;
//...省略
}
测试出现问题
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hHbpYV5w-1654251533302)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220326095320183.png)]
解决方法:
-
起别名
结果集映射
id name pwd id name password
- resultMap 元素是 MyBatis 中最重要最强大的元素
- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
- ResultMap 的优秀之处——你完全可以不用显式地配置它们。
如果一个数据库操作 出现了异常,我们需要排错,日志就是最好的工具
曾经:sout、debug
现在:日志工厂
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-s4MnkX5x-1654251533303)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220326102044646.png)]
- SLF4J
- LOG4J(deprecated since 3.5.9)
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING
- NO_LOGGING
在mybatis中具体使用哪一个日志实现,在设置中设定!
STDOUT_LOGGING标准日志输出
在mybatis核心配置文件中添加日志配置
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Y7KgJ1fM-1654251533304)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220326103056897.png)]
6.2、Log4J什么是Log4J
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件;
- 我们也可以控制每一条日志的输出格式;
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程;
- 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
-
导入log4j的包
log4j log4j 1.2.17 -
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=%d %p [%c] - %m%n #文件输出的相关配置 log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/zyy.log log4j.appender.file.MaxFileSize=10MB log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d %p [%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
-
配置log4j为mybatis日志的实现
-
使用log4j,运行测试
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iRIt0O1o-1654251533306)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220326110051525.png)]
简单使用
-
在要使用log4j的类中,导入包import org.apache.log4j.Logger;
-
日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
-
日志级别
@Test public void print() { logger.info("info..."); logger.debug("info..."); logger.error("info..."); }
思考:为啥要分页?
- 减少数据的处理量
-- 语法 select * from `user` limit startIndex,pageSize; select * from `user` limit 2; -- 相当于 select * from `user` limit 0,2;
使用mybatis实现分页,核心sql
-
接口
ListgetUserByLimit(Map map); -
Mapper.xml
select id, name, pwd from `user` limit #{startIndex},#{pageSize} -
测试
@Test public void getUserByLimit() { SqlSession sqlSession = null; try { sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Mapmap = new HashMap<>(16); map.put("startIndex", 0); map.put("pageSize", 2); List userList = mapper.getUserByLimit(map); for (User user : userList) { logger.info(user); } } finally { if (sqlSession != null) { sqlSession.close(); } } }
不在使用sql实现分压
-
接口
ListgetUserByRowBounds(); -
Mapper.xml
-
测试
@Test public void getUserByRowBounds() { SqlSession sqlSession = null; try { sqlSession = MybatisUtils.getSqlSession(); RowBounds rowBounds = new RowBounds(1,2); ListuserList = sqlSession.selectList("com.zyy.dao.UserMapper.getUserByRowBounds",null, rowBounds); for (User user : userList) { logger.info(user); } } finally { if (sqlSession != null) { sqlSession.close(); } } }
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-o75Ua3HH-1654251533306)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220326144801005.png)]
官方文档:MyBatis 分页插件 PageHelper
8、使用注解开发 8.1、面向接口编程- 根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好。
- 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不用那么重要了;
- 而各个对象之前的协作关系则成为系统设计的关键。小到不同类之前的通讯,大到各模块之间的交互,在系统设计之初都是要着重要考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
关于接口的理解
- 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离
- 接口的本身反映了系统设计人员对系统的抽象理解
- 接口应有两类:
- 第一类是对一个个体的抽象,它对应为一个抽象体(abstract class)
- 第二类是对一个个体某一方便的抽象,即形成一个抽象面(interface)
- 一个个体有可能有多个抽象面。抽象体和抽象面是有区别的。
三个面向区别
- 面向对象,我们考虑问题时,以对象为单位,考虑它的属性及方法
- 面向过程,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现
- 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题。更多的体现就是对系统整体的架构。
-
注解在接口上实现
@Select("select id, name, pwd from `user`") ListgetUserList(); -
需要在核心配置文件中绑定接口
-
测试
@Test public void getUserList() { SqlSession sqlSession = null; try { sqlSession = MybatisUtils.getSqlSession(); //底层主要应用反射 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); ListuserList = userMapper.getUserList(); for (User user : userList) { System.out.println(user.toString()); } } finally { if (sqlSession != null) { sqlSession.close(); } } }
本质:反射机制
底层:动态代理
mybatis详细的执行流程
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hl6mClHY-1654251533307)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/%E6%9C%AA%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6.png)]
8.3、CRUD我们可以造工具类创建的时候实现自动提交事务!
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession(true);
}
编写接口,增加注解
import com.zyy.pojo.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface UserMapper {
@Select("select id, name, pwd from `user`")
List getUserList();
@Select("select id, name, pwd from `user` where id=#{id} ")
User getUserById(@Param("id") int id);
@Insert("insert into `user`(id, name, pwd) values (#{id},#{name},#{password})")
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()中设定的属性名
import com.zyy.pojo.User;
import com.zyy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void getUserList() {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.getSqlSession();
//底层主要应用反射
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user.toString());
}
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
@Test
public void getUserById() {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.getSqlSession();
//底层主要应用反射
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);
System.out.println(user);
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
@Test
public void addUser() {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.getSqlSession();
//底层主要应用反射
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int count = userMapper.addUser(new User(6, "zyy6", "123456"));
System.out.println(count);
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
@Test
public void updateUser() {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.getSqlSession();
//底层主要应用反射
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int count = userMapper.updateUser(new User(6, "zyy2", "123123"));
System.out.println(count);
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
@Test
public void deleteUser() {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.getSqlSession();
//底层主要应用反射
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int count = userMapper.deleteUser(5);
System.out.println(count);
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
}
#{} ${}区别
(74条消息) mybatis中的#和 的 区 别 的 博 客 博 客 中 的 区 别 H o w a r d 1 4 的 博 客 − C S D N 博 客 m y b a t i s 中 的区别的博客博客中的区别_Howard_14的博客-CSDN博客_mybatis中 的区别的博客博客中的区别Howard14的博客−CSDN博客mybatis中和&区别
9、Lombok使用步骤
-
在idea中安装lombok插件
-
在项目中导入lombok的jar包
org.projectlombok lombok 1.18.22 -
在实体类上加注解即可
import lombok.AllArgsConstructor; import lombok.Data; @Data @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
实现原理:
99%的程序员都在用Lombok,原理竟然这么简单?我也手撸了一个!|建议收藏!!! - 云+社区 - 腾讯云 (tencent.com)
10、多对一处理多对一:
- 多个学生,对应一个老师
- 对于学生而言, 关联 ,多个学生,关联一个老师【多对一】
- 对于老师而言, 集合 ,一个老师有很多学生【一对多】
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AobR4FkR-1654251533308)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220331222349156.png)]
SQL
CREATE TABLE `teacher`
(
`id` INT(10) NOT NULL,
`name` VARCHAr(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE = INNODB
DEFAULT CHARSET = utf8;
INSERT INTO teacher(`id`, `name`)
VALUES (1, '秦老师');
CREATE TABLE `student`
(
`id` INT(10) NOT NULL,
`name` VARCHAr(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE = INNODB
DEFAULT CHARSET = utf8;
INSERT INTO `student` (`id`, `name`, `tid`)
VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`)
VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`)
VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`)
VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`)
VALUES ('5', '小王', '1');
测试环境搭建
- 导入lombok
- 新建实体类Teacher,Student
- 建立Mapper接口
- 建立Mapper.xml文件
- 在核心配置文件中绑定注册我们的Mapper接口或者文件【方式很多,自选】
- 测试查询是否能够成功!
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ts7IlUXw-1654251533309)(https://gitee.com/zhayuyao/img/raw/master/zhayuyao/img/image-20220331225454835.png)]
Student.java
@Data
public class Student {
private int id;
private String name;
private Teacher teacher;
}
Teacher.java
@Data
public class Teacher {
private int id;
private String name;
}
按照查询嵌套处理
按照结果嵌套处理
select s.id sId, s.name sName, t.name tName from student s,teacher t where s.tid=t.id;
回顾mysql多对一查询方式:
- 子查询
- 链表查询
比如:一个老师拥有多个学生!
对于老师而言,就是一对多的关系!
环境搭建实体类
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int tid;
}
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
private List studentList;
}
按照结果嵌套处理
按照查询嵌套处理select t.id tId,t.name tName,s.id sId,s.name sName from teacher t ,student s where t.id = s.tid and t.id=#{tId}
小结select id,name from teacher where id=#{tId} select id,name,tid from student where tid=#{tId}
- 关联 - association【多对一】
- 集合 - collection【一对多】
- javaType & ofType
- javaType 用来指定实体类中属性的类型
- ofType 用来指定映射到List或者集合中pojo类型,泛型中的约束类型。
- 保证sql的可读性,尽量保证通俗易懂
- 注意一对多和多对一中,属性和字段的问题
- 如果问题不好排查错误,可以使用日志,建议使用Log4j
面试高频:
- mysql引擎
- innodb底层原理
- 索引
- 索引优化



