文章目录
本文章涉及环境版本:
- mysql 5.7
- Mybatis 3.5.x
- Maven 3.6.x
- JDK 1.8
项目代码仓库:
https://github.com/Gang-bb/Study-Record/tree/main/bzhan-mybatis-study
需要clone整个bzhan-mybatis-study项目
(整体是一个maven多module工程)
该文章对应:《bzhan-mybatis-study01 》module项目
1. Mybatis概述
1.1 简介
- MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- MyBatis 本是apache的一个开源项目
iBatis
, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
1.2 如何获得Mybatis
-
maven仓库:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
-
Github : https://github.com/mybatis/mybatis-3/releases
-
中文文档:https://mybatis.org/mybatis-3/zh/index.html
1.3 持久化
数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 内存:断电即失
- 数据库(Jdbc),io文件持久化。
- 生活:冷藏. 罐头。
为什么需要需要持久化?
-
有一些对象,不能让他丢掉。
-
内存太贵了
1.4 持久层
Dao层,Service层,Controller层….
- 完成持久化工作的代码块
- 层界限十分明显。
1.5 为什么需要Mybatis
- 帮助程序猿将数据存入到数据库中。
- 方便
- 传统的JDBC代码太复杂了。简化。框架。自动化。
- 不用Mybatis也可以。更容易上手。 技术没有高低之分
- 优点:
- 简单易学
- 灵活
- sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql。
1.6 Mybatis开发工作流程
最重要的一点:使用的人多!
Spring SpringMVC SpringBoot
2 第一个Mybatis程序
思路:搭建环境–>导入Mybatis–>编写代码–>测试!
2.1 搭建环境
- 准备一个数据库和表
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'user1', '123456');
INSERT INTO `user` VALUES (2, 'user2', '111');
INSERT INTO `user` VALUES (3, 'user3', '222');
SET FOREIGN_KEY_CHECKS = 1;
- 新建项目
-
新建一个普通的maven项目
-
删除src目录
-
导入maven依赖
<!--导入依赖--> <dependencies> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--mybatis--> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> <scope>provided</scope> </dependency> </dependencies>
2.2 创建一个模块
-
编写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核心配置文件--> <configuration> <settings> <!-- 用于数据库用下划线 实体类用驼峰 的自动转换识别--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis-study?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> </configuration>
-
编写mybatis工具类
public class MybatisUtil { /** * 静态属性属于类不属于对象,且全局唯一 */ private static SqlSessionFactory sqlSessionFactory; //利用静态块再初始化类时实例化SqlSessionFactory static { try { //方法1: 构造者模式.初始化sqlSessionFactory,解析配置文件 Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); //方法2: 用流 // String resource = "mybatis-config.xml"; // InputStream inputStream = Resources.getResourceAsStream(resource); // sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); //抛出一个类初始化过程中的错误 throw new ExceptionInInitializerError(e); } } //工具类一般都用static,通过 类名.xx() 调用 /** * openSession 创建一个新的SqlSession对象 * @return SqlSession对象 */ public static SqlSession openSession(){ return sqlSessionFactory.openSession(); } /** * 释放一个有效的SqlSession对象 * @param session 即将释放的SqlSession对象 */ public static void closeSession(SqlSession session){ if(session != null){ session.close(); } } }
2.3 编写代码
- 实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private String password;
}
- Dao层mapper接口
public interface UserMapper {
List<User> getUserList();
}
- Mapper的.xml文件
此步骤时,如果你的UserMapper.xml文件放到了非resourse目录下,会出现
org.apache.ibatis.binding.BindingException: Type interface xxx.xxx.xx.UserMapper is not known to the MapperRegistry.
需要在pom.xml文件中添加打包的配置:
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<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>
常设置的目录:
内容:
<?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=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.gangbb.model.dao.UserMapper">
<!--select查询语句-->
<select id="getUserList" resultType="com.gangbb.model.pojo.User">
select * from mybatis-study.user
</select>
</mapper>
namespace:
namespace中的包名要和 Dao/mapper 接口的包名一致!
再返回mybatis-config.xml配置文件中对它进行声明注册:
<mappers>
<mapper resource="mappers/UserMapper.xml"/>
</mappers>
2.4 测试
- Junit单元测试
@Test
public void TestUserMapper(){
SqlSession sqlSession = null;
try {
//1. 获取sqlsession对象
sqlSession = MybatisUtil.openSession();
//2.方式一: getMapper
// UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// List<User> userList = userMapper.getUserList();
//方式二:
List<User> userList = sqlSession.selectList("getUserList");
for (User user: userList){
System.out.println(user);
}
} finally {
//3. 关闭sqlsession
sqlSession.close();
}
}
推荐使用方式一,方式二耦合度过高!
可能会报错:
可能原因:
useSSL一定要是false!
正常的运行结果:
还可能遇到其他问题:
- 配置文件没有注册
- 绑定接口错误。
- 方法名不对
- 返回类型不对
- Maven导出资源问题