1、MyBatis简介
1.1、MyBatis历史
MyBatis最初是Apache 的一个开源项目iBatis , 2010年6月这个项目由Apache Software Foundation迁移到了Google Code。随着开发团队转投Google Code旗下, iBatis3.x正式更名为MyBatis。代码于2013年11月迁移到Github 。
iBatis一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。 iBatis提供的持久层框架
包括SQL Maps和Data Access Objects(DAO)。
1.2、MyBatis特性
MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架
MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集
MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old JavaObjects ,普通的Java对象)映射成数据库中的记录
MyBatis 是一个 半自动的ORM(Object Relation Mapping)框架
1.3、MyBatis下载
MyBatis下载地址:https://github.com/mybatis/mybatis-3
1.4、和其它持久化层技术对比
JDBC
SQL 夹杂在Java代码中耦合度高,导致硬编码内伤
维护不易且实际开发需求中 SQL 有变化,频繁修改的情况多见
代码冗长,开发效率低
Hibernate 和 JPA
操作简便,开发效率高
程序中的长难复杂 SQL 需要绕过框架
内部自动生产的 SQL,不容易做特殊优化
基于全映射的全自动框架,大量字段的 POJO 进行部分映射时比较困难。
反射操作太多,导致数据库性能下降
MyBatis
轻量级,性能出色
SQL 和 Java 编码分开,功能边界清晰。Java代码专注业务、SQL语句专注数据
开发效率稍逊于HIbernate,但是完全能够接受
2、搭建MyBatis
2.1、开发环境
IDE:idea 2021.3
构建工具:maven 3.8.6
MySQL版本:MySQL 8
MyBatis版本:MyBatis 3.5.10
MySQL不同版本的注意事项
1、驱动类driver-class-name
MySQL 5版本使用jdbc5驱动,驱动类使用:com.mysql.jdbc.Driver
MySQL 8版本使用jdbc8驱动,驱动类使用:com.mysql.cj.jdbc.Driver
2、连接地址url
MySQL 5版本的url:
jdbc:mysql://localhost:3306/ssm
MySQL 8版本的url:
jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
否则运行测试用例报告如下错误:
java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or
represents more
2.2、创建maven工程
1> 打包方式:jar
2> 引入依赖
pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <dependencies > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.5.7</version > </dependency > <dependency > <groupId > junit</groupId > <artifactId > junit</artifactId > <version > 4.12</version > <scope > test</scope > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 8.0.16</version > </dependency > </dependencies >
2.3、创建MyBatis的核心配置文件
习惯上命名为mybatis-config.xml
,这个文件名仅仅只是建议,并非强制要求(最好还是这样铭铭)。
将来整合Spring之后,这个配置文件可以省略,所以大家操作时可以直接复制、粘贴。
核心配置文件主要用于配置连接数据库的环境以及MyBatis的全局配置信息
核心配置文件存放的位置是src/main/resources目录下
后续直接在idea 创建文件模板,高效复用
mybatis-config.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?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" /> <dataSource type ="POOLED" > <property name ="driver" value ="com.mysql.cj.jdbc.Driver" /> <property name ="url" value ="jdbc:mysql://localhost:3306/ssm? serverTimezone=UTC" /> <property name ="username" value ="root" /> <property name ="password" value ="123456" /> </dataSource > </environment > </environments > <mappers > <package name ="mappers/UserMapper.xml" /> </mappers > </configuration >
2.4、创建mapper接口
MyBatis中的mapper接口相当于以前的dao。但是区别在于,mapper仅仅是接口,我们不需要提供实现类。
UserMapper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 package pers.dhx_.mapper;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Param;import pers.dhx_.pojo.User;import java.util.List;import java.util.Map;public interface UserMapper { int insertUser (User user) ; void updateUser (User user) ; void deleteUser (Integer id) ; User getUserById () ; List<User> getAllUser () ; User checkLogin (String username, String password) ; User checkLoginByMap (Map<String,Object> map) ; User checkLoginByParam (@Param("username") String username, @Param("password") String password) ; }
2.5、创建MyBatis的映射文件
Java概念
数据库概念
类
表
属性
字段
对象
记录、 行 、 值
1、映射文件的命名规则:
表所对应的实体类的类名+Mapper.xml
例如:表t_user,映射的实体类为User,所对应的映射文件为UserMapper.xml
因此一个映射文件对应一个实体类,对应一张表的操作
MyBatis映射文件用于编写SQL,访问以及操作表中的数据
MyBatis映射文件存放的位置是src/main/resources/mappers目录下
2、 MyBatis中可以面向接口操作数据,要保证两个一致:
mapper接口的全类名和映射文件的命名空间(namespace)保持一致
mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致
***Mapper.xml 模板
1 2 3 4 5 6 <?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" > <mapper namespace ="${PACKAGE_NAME}.${NAME}" > </mapper >
UserMapper.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 <?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" > <mapper namespace ="pers.dhx_.mapper.EmpMapper" > <select id ="getUserById" resultType ="pers.dhx_.pojo.User" > select *from t_user where id=3; </select > <select id ="getAllUser" resultType ="User" > select *from t_user ; </select > <select id ="checkLogin" resultType ="User" > select *from t_user where username=#{arg0} and password=#{arg1} ; </select > <select id ="checkLoginByMap" resultType ="User" > select *from t_user where username= #{username} and password=#{password} ; </select > <insert id ="insertUser" > insert into t_user values(null,#{username},#{password},#{age},#{gender},#{email}); </insert > <select id ="checkLoginByParam" resultType ="User" > select *from t_user where username=#{username} and password=#{password}; </select > </mapper >
2.6、通过junit测试功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 @Test public void test1 () throws Exception{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml" ); SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder (); SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true ); UserMapper mapper = sqlSession.getMapper(UserMapper.class); sqlSession.close(); } @Test public void TestSQlSession () throws IOException { SqlSession sqlSession = SqlSessionUtil.getSqlSession(); var mapper = sqlSession.getMapper(UserMapper.class); mapper.insertUser(new User ("Aymy" ,"pwd" ,42 ,"女" ,"645634532@qw.com" )); sqlSession.close(); } @Test public void updateTest () throws IOException { InputStream is = Resources.getResourceAsStream("mybatis-config.xml" ); SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder (); SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true ); var mapper = sqlSession.getMapper(UserMapper.class); mapper.updateUser(new User ("Aymy" ,"pwd" ,42 ,"女" ,"645634532@qw.com" )); sqlSession.close(); } @Test public void deleteTest () throws IOException { InputStream is = Resources.getResourceAsStream("mybatis-config.xml" ); SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder (); SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true ); var mapper = sqlSession.getMapper(UserMapper.class); mapper.deleteUser(13 ); sqlSession.close(); } @Test public void selectTest1 () throws IOException { var is = Resources.getResourceAsStream("mybatis-config.xml" ); SqlSession sqlSession= (new SqlSessionFactoryBuilder ()).build(is).openSession(true ); var mapper = sqlSession.getMapper(UserMapper.class); System.out.println(mapper.getUserById()); } @Test public void checkLoginTest () throws IOException { var is = Resources.getResourceAsStream("mybatis-config.xml" ); SqlSession sqlSession= (new SqlSessionFactoryBuilder ()).build(is).openSession(true ); var mapper = sqlSession.getMapper(UserMapper.class); System.out.println(mapper.checkLoginByParam("admin1" , "123456" )); } @Test public void checkLoginByMapTest () throws IOException { Map<String,Object> map=new HashMap <>(); var is = Resources.getResourceAsStream("mybatis-config.xml" ); SqlSession sqlSession= (new SqlSessionFactoryBuilder ()).build(is).openSession(true ); var mapper = sqlSession.getMapper(UserMapper.class); map.put("admin1" ,"123456" ); map.put("root" ,"23423" ); System.out.println(mapper.checkLoginByMap(map)); } @Test public void InsertMuch () throws IOException { var sqlSession = SqlSessionUtil.getSqlSession(); var mapper = sqlSession.getMapper(UserMapper.class); int times=50 ; while (times--!=0 ) { String username= MyStringUtil.genericRandomLetter(3 ); String password= MyStringUtil.genericRandomLetter(3 )+MyStringUtil.genericRandomNumber(5 ); int age= Integer.parseInt(MyStringUtil.genericRandomNumber(2 )); String email=MyStringUtil.genericRandomNumber(10 )+"@qq.com" ; mapper.insertUser(new User (username,password,age,"男" ,email)); } }
可以发现上方又很多的重复代码:构造SqlSession
注意点:
当SQLSessionFactory.openSession(boolean b); 参数为true 是, SqlSession会自动提交事务,不需要手动提交
也就是可以省略sqlSession.commit();
SqlSessionUtil.java
1 2 3 4 5 6 public class SqlSessionUtil { public static SqlSession getSqlSession () throws IOException { var resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml" ); return new SqlSessionFactoryBuilder ().build(resourceAsStream).openSession(true ); } }
MyStringUtil.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public class MyStringUtil { public static String genericRandomNumber (int size) { StringBuffer res=new StringBuffer ("" ); while (size--!=0 ) { res.append((char )(Math.random()*100 %10 +48 )); } return res.toString(); } public static String genericRandomLetter (int size) { StringBuffer res=new StringBuffer ("" ); if (size==3 ) res.append((char )(Math.random()*100 %26 +97 )); while (size--!=0 ) { res.append((char )(Math.random()*100 %26 +65 )); } return res.toString().toLowerCase(Locale.ROOT); } }
2.7、加入log4j日志功能
1>加入依赖
1 2 3 4 5 6 <dependency > <groupId > log4j</groupId > <artifactId > log4j</artifactId > <version > 1.2.17</version > </dependency >
2>加入log4j的配置文件
log4j的配置文件名为log4j.xml,存放的位置是src/main/resources目录下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j :configuration SYSTEM "log4j.dtd" > <log4j:configuration xmlns:log4j ="http://jakarta.apache.org/log4j/" > <appender name ="STDOUT" class ="org.apache.log4j.ConsoleAppender" > <param name ="Encoding" value ="UTF-8" /> <layout class ="org.apache.log4j.PatternLayout" > <param name ="ConversionPattern" value ="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" /> </layout > </appender > <logger name ="java.sql" > <level value ="debug" /> </logger > <logger name ="org.apache.ibatis" > <level value ="info" /> </logger > <root > <level value ="debug" /> <appender-ref ref ="STDOUT" /> </root > </log4j:configuration >
日志的级别
FATAL(致命)>ERROR(错误)>WARN(警告)>INFO(信息)>DEBUG(调试)
3、核心配置文件详解
核心配置文件中的标签必须按照固定的顺序(标签的书写顺序):
properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,refl
ectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 <?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 > <properties resource ="jdbc.properties" /> <typeAliases > <typeAlias type ="pers.dhx_.mapper.EmpMapper" alias ="UserMapper" /> <package name ="pers.dhx_.pojo" /> </typeAliases > <environments default ="development" > <environment id ="development" > <transactionManager type ="JDBC" /> <dataSource type ="POOLED" > <property name ="driver" value ="${jdbc.driver}" /> <property name ="url" value ="${jdbc.url}" /> <property name ="username" value ="${jdbc.username}" /> <property name ="password" value ="${jdbc.password}" /> </dataSource > </environment > </environments > <mappers > <package name ="pers.dhx_.mapper" /> !--<mapper resource ="mappers/UserMapper.xml" /> --> </mappers > </configuration >
jdbc.properties
1 2 3 4 jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql: jdbc.username=root jdbc.password=****
mybatis使用package方式映射mapper报错
在初学mybatis通过junit测试功能时系统一直报
Mapped Statements collection does not contain value for pers.dhx_.DAO.UserMapper.insertUser
大概意思是mybatis无法找到UserMapper的映射文件
也就是识别UserMapper.xml过程中出问题了
测试的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Test public void test1 () throws Exception{ InputStream is = Resources.getResourceAsStream("mybatis-config.xml" ); SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder (); SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true ); UserMapper mapper = sqlSession.getMapper(UserMapper.class); System.out.println(mapper.insertUser()); sqlSession.close(); }
原本是将UserMapper.xml放在resources目录下
UerMapper.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <?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" > <mapper namespace ="pers.dhx_.mapper.UserMapper" > <insert id ="insertUser" > insert into t_user values(null,'admin1','123456',23,'男','12345@qq.com') </insert > </mapper >
后来查阅资料发现错误原因是, 如果使用package标签映射mapper文件 , resources目录和java目录中的 xml文件要与 接口对应
看图就明白了
教程里面的老师没有说这个 ,但是也应该注意
其他映射mapper的方法
mapper标签使用resource映射
mybatis-config.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?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" /> <dataSource type ="POOLED" > <property name ="driver" value ="com.mysql.cj.jdbc.Driver" /> <property name ="url" value ="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC" /> <property name ="username" value ="root" /> <property name ="password" value ="${password}" /> </dataSource > </environment > </environments > <mappers > <mapper resource ="pers/dhx_/mapper/UserMapper.xml" /> </mappers > </configuration >
附上resources目录
mapper标签使用class映射
class 注意要写全类名
需要注意的是这里需要在接口的方法上面写上对应的注解
UserMapper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 package pers.dhx_.mapper;import org.apache.ibatis.annotations.Insert;public interface UserMapper { @Insert(value = "insert into t_user values(null,'admin','123456',23,'男','12345@qq.com')") int insertUser () ; }
mybatis-config.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?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" /> <dataSource type ="POOLED" > <property name ="driver" value ="com.mysql.cj.jdbc.Driver" /> <property name ="url" value ="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC" /> <property name ="username" value ="root" /> <property name ="password" value ="${password}" /> </dataSource > </environment > </environments > <mappers > <mapper class ="pers.dhx_.mapper.UserMapper" /> </mappers > </configuration >
mapper标签使用url映射
其实就是使用绝对路径
1 2 3 4 5 <configuration > <mappers > <mapper url ="file:///C:/User/lenovo/Desktop/mappers/UserMapper" /> </mappers > </configuration >