文章目录
【框架】Mybatis简单使用
1、Mybatis概述
1.1、Mybatis概念
MyBatis 是一款优秀的持久层框架,用于简化 JDBC 开发
MyBatis 本是 Apache 的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github
官网:https://mybatis.org/mybatis-3/zh/index.html
持久层:
-
负责将数据到保存到数据库的那一层代码。
以后开发我们会将操作数据库的Java代码作为持久层。而Mybatis就是对jdbc代码进行了封装。
-
JavaEE三层架构:表现层、业务层、持久层
三层架构在后期会给大家进行讲解,今天先简单的了解下即可。
框架:
- 框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型
- 在框架的基础之上构建软件编写更加高效、规范、通用、可扩展
举例给大家简单的解释一下什么是半成品软件。大家小时候应该在公园见过给石膏娃娃涂鸦
如下图所示有一个石膏娃娃,这个就是一个半成品。你可以在这个半成品的基础上进行不同颜色的涂鸦
了解了什么是Mybatis后,接下来说说以前 JDBC代码
的缺点以及Mybatis又是如何解决的。
1.2 、JDBC 缺点
下面是 JDBC 代码,我们通过该代码分析都存在什么缺点:
-
硬编码
-
注册驱动、获取连接
上图标1的代码有很多字符串,而这些是连接数据库的四个基本信息,以后如果要将Mysql数据库换成其他的关系型数据库的话,这四个地方都需要修改,如果放在此处就意味着要修改我们的源代码。
-
SQL语句
上图标2的代码。如果表结构发生变化,SQL语句就要进行更改。这也不方便后期的维护。
-
-
操作繁琐
-
手动设置参数
-
手动封装结果集
上图标4的代码是对查询到的数据进行封装,而这部分代码是没有什么技术含量,而且特别耗费时间的。
-
1.3、Mybatis优化
- 硬编码可以配置到配置文件
- 操作繁琐的地方mybatis都自动完成
如图所示
2、Mybatis快速入门
需求:查询stu表中所有的数据
2.1、项目搭建环境
- 项目构建工具maven-3.6.0
- idea2018.1
- mysql5.7.37
2.2、创建stu表,添加数据
create table `stu` (
`id` int (11),
`name` varchar (60),
`age` int (11),
`sex` varchar (15),
`address` varchar (300),
`math` double ,
`english` double ,
`hire_date` date
);
insert into `stu` (`id`, `name`, `age`, `sex`, `address`, `math`, `english`, `hire_date`) values('1','马运','55','男','杭州','66.00','78.00','1995-09-01');
insert into `stu` (`id`, `name`, `age`, `sex`, `address`, `math`, `english`, `hire_date`) values('2','马花疼','45','女','深圳','98.00','87.0
0','1998-09-01');
insert into `stu` (`id`, `name`, `age`, `sex`, `address`, `math`, `english`, `hire_date`) values('3','马斯克','55','男','香港','56.00','77.00','1999-09-02');
insert into `stu` (`id`, `name`, `age`, `sex`, `address`, `math`, `english`, `hire_date`) values('4','柳白','20','女','湖南','76.00','65.00','1997-09-05');
insert into `stu` (`id`, `name`, `age`, `sex`, `address`, `math`, `english`, `hire_date`) values('5','柳青','20','男','湖南','86.00','55.00','1998-09-01');
insert into `stu` (`id`, `name`, `age`, `sex`, `address`, `math`, `english`, `hire_date`) values('6','刘德花','57','男','香港','99.00','99.00','1998-09-01');
insert into `stu` (`id`, `name`, `age`, `sex`, `address`, `math`, `english`, `hire_date`) values('7','张学右','22','女','香港','99.00','99.00','1998-09-01');
insert into `stu` (`id`, `name`, `age`, `sex`, `address`, `math`, `english`, `hire_date`) values('8','德玛西亚','18','男','南京','56.00','65.00','1994-09-02');
insert into `stu` (`id`, `name`, `age`, `sex`, `address`, `math`, `english`, `hire_date`) values('10','周良成','18','男','四川成都','100.00','90.00','2003-12-28');
2.3、创建模块,导入坐标
在创建好的模块中的 pom.xml 配置文件中添加依赖的坐标
<dependencies>
<!--mybatis 依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--mysql 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!--junit 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- 添加slf4j日志api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
</dependency>
<!-- 添加logback-classic依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- 添加logback-core依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<!--添加lombok辅助-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
注意:需要在项目的 resources
目录下创建logback的配置文件
logback.xml
配置文件内容如下
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--
CONSOLE :表示当前的日志信息是可以输出到控制台的。
-->
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
</encoder>
</appender>
<logger name="com.qfedu" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
</logger>
<!--
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
, 默认debug
<root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
-->
<root level="DEBUG">
<appender-ref ref="Console"/>
</root>
</configuration>
2.4、编写MyBatis核心配置文件-- > 替换连接信息 解决硬编码问题
在模块下的 resources
目录下创建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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!--
下面的proerty值修改成你们的数据库信息
· -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db1?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="1948"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
2.5、编写 SQL 映射文件–>统一管理sql语句,解决硬编码问题
在模块的 resources
目录下创建映射配置文件 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:名称空间
resultType的值修改成对应的pojo类
-->
<mapper namespace="test">
<select id="selectUsers" resultType="com.qfedu.pojo.User">
select * from stu
</select>
</mapper>
2.6、编码
2.6.1、在com.qfedu.pojo
包下创建User类
/**
* @Author ZhouLiangCheng
* @Date 2022/6/24
* @Description
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private int age;
private String sex;
private String address;
private int math;
private int english;
private String hire_date;
}
2.6.2、在com.qfedu
包下编写MyBatisDemo测试类
/**
* @Author ZhouLiangCheng
* @Date 2022/6/24
* @Description
*/
public class MyBatisDemo {
public static void main(String[] args) throws IOException {
//1.加载mybatis的核心配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取sql
List<User> users = sqlSession.selectList("test.selectUsers");
System.out.println(users);
}
}
本文简单的描述了Mybatis的简单使用方法,更高级的使用可以去看MyBatis官网了解具体使用方法,此文不再赘述。