Mybatis 基础介绍与逆向工程的构建
Mybatis系列:
Mybatis 基础介绍与逆向工程的构建 :https://www.jianshu.com/p/1c18db4d7a38
Mybatis 源码分析(一)之 Mybatis 的Executor的初始化:https://www.jianshu.com/p/c7425c841337
Mybatis 源码分析(二)之 Mybatis 操作数据库的流程 :https://www.jianshu.com/p/11d354ec3612
Mybatis 源码分析(三)之 Mybatis 的一级缓存和二级缓存 :https://www.jianshu.com/p/5515640d14fe
优秀博客:
http://www.mybatis.org/mybatis-3/zh/index.html
http://www.mybatis.org/generator/index.html
为什么要用Mybatis?
先看下我们传统JDBC连接数据库的弊端:
jdbc 底层没有用连接池、操作数据库需要频繁的创建和关联链接。消耗很大的资源
写原生的 jdbc 代码在java中,一旦我们要修改sql的话,java需要整体编译,不利于系统维护
使用 PreparedStatement 预编译的话对变量进行设置 123 数字,这样的序号不利于维护
返回 result 结果集也需要硬编码。
什么是 MyBatis ?
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
这么看一下,是不是感觉mybatis全给解决了。
开始构建Mybatis工程
pom.xml
4.0.0
com.demo
mybatis-test
1.0-SNAPSHOT
org.mybatis
mybatis
3.3.0
mysql
mysql-connector-java
5.1.29
junit
junit
4.11
test
log4j
log4j
1.2.17
org.slf4j
slf4j-api
1.7.12
org.slf4j
slf4j-log4j12
1.7.12
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.7
mysql
mysql-connector-java
5.1.29
项目目录结构
mybatis-config.xml
属性名 | 作用 |
---|---|
属性(peoperties) | 系统属性占用配置 |
设置(settings) | 用于修改Mybatis的运行时行为 |
类型别名(typeAliases) | 为类型建立别名,一般使用更短的名称代替 |
类型处理器(typeHanders) | 用于将预编译语句(PreparedStatement)或者结果集(ResultSet)中的JDBC类型转换为Java类型 |
对象工厂(ObjectFactory) | 提供默认构造器或执行构造器参数初始化目标类型的对象 |
插件(plugins) | Mybatis提供插件的方式来拦截映射(可以根据自己的需求进行编写插件) |
环境(environments) | Mybatis运行配置多个环境 |
数据库标识提供商(databaseIdProvider) | 数据库标识提供商 |
SQL映射文件(mappers) | SQL映射文件 |
其中的SQL映射文件mappers如下:
mapper文件可以配置4种,源码种最先的是package,如果package没有,则是其余三种,4种里面只能选择一种配置。
源码地址:
org.apache.ibatis.builder.xml.XMLConfigBuilder#mapperElement
//mapper元素解析,获得各种crud操作或者配置文件
private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
if ("package".equals(child.getName())) {
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
InputStream inputStream = Resources.getResourceAsStream(resource);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url != null && mapperClass == null) {
ErrorContext.instance().resource(url);
InputStream inputStream = Resources.getUrlAsStream(url);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url == null && mapperClass != null) {
Class> mapperInterface = Resources.classForName(mapperClass);
configuration.addMapper(mapperInterface);
} else {
throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
}
}
}
}
}
mysql.properties (安装mysql数据库)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.5.104:3306/mybatis
jdbc.username=root
jdbc.password=root
建表语句
CREATE TABLE `user` (
`id` int(16) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`name` varchar(32) DEFAULT NULL COMMENT '用户名',
`age` int(4) DEFAULT NULL COMMENT '年龄',
PRIMARY KEY (`id`),
UNIQUE KEY `index_id` (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
log4j.properties
### 设置###
log4j.rootLogger = debug,stdout,D,E
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
什么是逆向工程(http://www.mybatis.org/generator/index.html):
MyBatis 的一个主要的特点就是需要程序员自己编写 sql,那么如果表太多的话,难免会很麻烦,所以 mybatis 官方提供了一个逆向工程,可以针对单表自动生成 mybatis 执行所需要的代码(包括 mapper.xml、mapper.java、po..)。一般在开发中,常用的逆向工程方式是通过数据库的表生成
generatorConfig.xml
这些文件创建好之后,进入你的pom文件地址,使用maven命令,逆向生成我们需要的pojo、mapper等文件。
mvn mybatis-generator:generate
生成情况如下
D:\dev\code\demo\mybatis-test>mvn mybatis-generator:generate
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------------< com.demo:mybatis-test >------------------------
[INFO] Building mybatis-test 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- mybatis-generator-maven-plugin:1.3.7:generate (default-cli) @ mybatis-test ---
[WARNING] Existing file not overwritten, the generated file is saved as D:\dev\code\demo\mybatis-test\.\src\main\java\com\demo\mybatis\pojo\Food.java.2
[WARNING] Existing file not overwritten, the generated file is saved as D:\dev\code\demo\mybatis-test\.\src\main\java\com\demo\mybatis\mapper\FoodMapper.java.1
[WARNING] Existing file not overwritten, the generated file is saved as D:\dev\code\demo\mybatis-test\.\src\main\java\com\demo\mybatis\mapper\FoodSqlProvider.java.1
[WARNING] Existing file not overwritten, the generated file is saved as D:\dev\code\demo\mybatis-test\.\src\main\java\com\demo\mybatis\pojo\User.java.2
[WARNING] Existing file not overwritten, the generated file is saved as D:\dev\code\demo\mybatis-test\.\src\main\java\com\demo\mybatis\mapper\UserMapper.java.1
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.802 s
[INFO] Finished at: 2019-01-26T19:48:50+08:00
[INFO] ------------------------------------------------------------------------
D:\dev\code\demo\mybatis-test>
创建测试类:MybatisTest.java
package com.demo.mybatis;
import com.demo.mybatis.mapper.UserMapper;
import com.demo.mybatis.pojo.User;
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 org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Reader;
/**
* com.demo.mybatis
*
* @author Zyy
* @date 2019/1/26 18:13
*/
public class MybatisTest {
private static final Logger logger = LoggerFactory.getLogger(MybatisTest.class);
@Test
public void test01() throws IOException {
String resource = "mybatis-config.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
User user = session.selectOne("selectByPrimaryKey", 1);
session.commit();
logger.info(user.toString());
}
@Test
public void test02() throws IOException {
String resource = "mybatis-config.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectByPrimaryKey(2);
logger.info(user.toString());
}
//user.dir可以用来打印你当然目录地址,如果有需要可以替换配置文件中的地址
@Test
public void test03() throws IOException {
System.out.println(System.getProperty("user.dir"));
}
}
执行结果信息:
[DEBUG] 2019-01-26 23:34:08,755 method:org.apache.ibatis.logging.LogFactory.setImplementation(LogFactory.java:135)
Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
[DEBUG] 2019-01-26 23:34:08,891 method:org.apache.ibatis.datasource.pooled.PooledDataSource.forceCloseAll(PooledDataSource.java:316)
PooledDataSource forcefully closed/removed all connections.
[DEBUG] 2019-01-26 23:34:08,892 method:org.apache.ibatis.datasource.pooled.PooledDataSource.forceCloseAll(PooledDataSource.java:316)
PooledDataSource forcefully closed/removed all connections.
[DEBUG] 2019-01-26 23:34:08,892 method:org.apache.ibatis.datasource.pooled.PooledDataSource.forceCloseAll(PooledDataSource.java:316)
PooledDataSource forcefully closed/removed all connections.
[DEBUG] 2019-01-26 23:34:08,893 method:org.apache.ibatis.datasource.pooled.PooledDataSource.forceCloseAll(PooledDataSource.java:316)
PooledDataSource forcefully closed/removed all connections.
[DEBUG] 2019-01-26 23:34:08,958 method:org.apache.ibatis.transaction.jdbc.JdbcTransaction.openConnection(JdbcTransaction.java:138)
Opening JDBC Connection
[DEBUG] 2019-01-26 23:34:09,231 method:org.apache.ibatis.datasource.pooled.PooledDataSource.popConnection(PooledDataSource.java:387)
Created connection 1511785794.
[DEBUG] 2019-01-26 23:34:09,232 method:org.apache.ibatis.transaction.jdbc.JdbcTransaction.setDesiredAutoCommit(JdbcTransaction.java:102)
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@5a1c0542]
[DEBUG] 2019-01-26 23:34:09,252 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:142)
==> Preparing: select id, name, age from user where id = ?
[DEBUG] 2019-01-26 23:34:09,301 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:142)
==> Parameters: 1(Integer)
[DEBUG] 2019-01-26 23:34:09,331 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:142)
<== Total: 1
[INFO ] 2019-01-26 23:34:09,332 method:com.demo.mybatis.MybatisTest.test01(MybatisTest.java:32)
User{id=1, name='ayang', age=18}
其中的注意事项:
逆向工程配置文件
generatorConfig.xml中,javaClientGenerator可以选择XMLMAPPER(xml文件形式)、ANNOTATEDMAPPER(注解形式)两种类型,还有一种example,感觉这种不好使,是在另个参数里面配置的。
选择XMLMAPPER(xml文件形式)生成的如下:
ANNOTATEDMAPPER(注解形式)生成的如下:
@Select({
"select",
"id, name, age",
"from user",
"where id = #{id,jdbcType=INTEGER}"
})
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),
@Result(column="age", property="age", jdbcType=JdbcType.INTEGER)
})
User selectByPrimaryKey(Integer id);
对比:
Xml:增加 xml 文件、麻烦、条件不确定、容易出错,特殊字符转义
注释:不适合复杂 sql,收集 sql 不方便,重新编译
parameterType 与 parameterMap 区别:
通过 parameterType 指定输入参数的类型,类型可以是简单类型、hashmap、pojo 的包装类型
resultType 与 resultMap 区别
使用 resultType 进行输出映射,只有查询出来的列名和 pojo 中的属性名一致,该列才可以
映射成功。
mybatis 中使用 resultMap 完成高级输出结果映射。
参数标记符号之#与$的区别
# 预编译,防止 sql 注入(推荐)
$可以 sql 注入,代替作用
搞定:)
接下来进行重要特性了解与源码分析:)