- 1.Mybatis概述
- 1.1 Mybatis概念
- 1.2 Mybatis优化
- 1.2 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代码进行了封装。
- 硬编码可以配置到配置文件
- 操作频繁的地方mybatis都可以自动完成
需求:查询user表中所有的数据
- 创建user表,添加数据
create database mybatis; use mybatis; drop table if exists tb_user; create table tb_user( id int primary key auto_increment, username varchar(20), password varchar(20), gender char(1), addr varchar(30) ); INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '男', '北京'); INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津'); INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');
- 创建模块,导入坐标
在创建好的模块中的 pom.xml 配置文件中添加依赖的坐标
org.mybatis mybatis 3.5.5 mysql mysql-connector-java 5.1.46 junit junit 4.13 test org.slf4j slf4j-api 1.7.20 ch.qos.logback logback-classic 1.2.3 ch.qos.logback logback-core 1.2.3
注意:需要在项目的resources目录下创建logback的配置文件
- 编写MyBatis核心配置文件(替换连接信息 解决硬编码问题)
在模块下的resources目录下创建mybatis的配置文件“mybatis-config.xml”,内容如下:
- 编写SQL映射文件(统一管理SQL语句,解决硬编码问题)
在模块的resources目录下常见映射配置文件usermapper.xml,内容如下:
- 编码
在cn.hncj.pojoc包下创建User类
public class User {
private int id;
private String username;
private String password;
private String gender;
private String addr;
//省略了 setter 和 getter
}
在 cn.hncj 包下编写 MybatisDemo 测试类
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 users = sqlSession.selectList("test.selectAll"); //参数是一个字符串,该 字符串必须是映射配置文件的namespace.id
System.out.println(users);
//4. 释放资源
sqlSession.close();
}
}
解决SQL映射文件的警告提示:



