Mybatis 基础介绍与逆向工程的构建
Mybatis系列:
Mybatis 基础介绍与逆向工程的构建 ://www.greatytc.com/p/1c18db4d7a38
Mybatis 源码分析(一)之 Mybatis 的Executor的初始化://www.greatytc.com/p/c7425c841337
Mybatis 源码分析(二)之 Mybatis 操作数据库的流程 ://www.greatytc.com/p/11d354ec3612
Mybatis 源码分析(三)之 Mybatis 的一级缓存和二级缓存 ://www.greatytc.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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo</groupId>
<artifactId>mybatis-test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- junit测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 日志文件管理包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
</dependencies>
<!-- 逆向工程插件 -->
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
项目目录结构
mybatis-config.xml
属性名 | 作用 |
---|---|
属性(peoperties) | 系统属性占用配置 |
设置(settings) | 用于修改Mybatis的运行时行为 |
类型别名(typeAliases) | 为类型建立别名,一般使用更短的名称代替 |
类型处理器(typeHanders) | 用于将预编译语句(PreparedStatement)或者结果集(ResultSet)中的JDBC类型转换为Java类型 |
对象工厂(ObjectFactory) | 提供默认构造器或执行构造器参数初始化目标类型的对象 |
插件(plugins) | Mybatis提供插件的方式来拦截映射(可以根据自己的需求进行编写插件) |
环境(environments) | Mybatis运行配置多个环境 |
数据库标识提供商(databaseIdProvider) | 数据库标识提供商 |
SQL映射文件(mappers) | SQL映射文件 |
<?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="mysql.properties"/>
<settings>
<!--全局性设置懒加载。如果设为‘false’,则所有相关联的都会被初始化加载,默认值为false-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--当设置为‘true’的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。默认值为true-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<typeAliases>
<!-- 其实就是将bean的替换成一个短的名字-->
<typeAlias type="com.demo.mybatis.pojo.User" alias="User"/>
</typeAliases>
<!--对事务的管理和连接池的配置-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED"><!--POOLED:使用Mybatis自带的数据库连接池来管理数据库连接-->
<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>
<!--mapping文件路径配置-->
<mappers>
<!--<mapper resource="mapper/UserMapper.xml"/>-->
<mapper class="com.demo.mybatis.mapper.UserMapper"/>
<!--<package name="com.demo.mybatis.mapper"/>-->
<!--<mapper url=""/>-->
</mappers>
</configuration>
其中的SQL映射文件mappers如下:
<!--mapping文件路径配置-->
<mappers>
<!--<mapper resource="mapper/UserMapper.xml"/>-->
<mapper class="com.demo.mybatis.mapper.UserMapper"/>
<!--<package name="com.demo.mybatis.mapper"/>-->
<!--<mapper url=""/>-->
</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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="sqlserverTables" targetRuntime="MyBatis3">
<!-- 生成的pojo,将implements Serializable -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 数据库链接URL、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.5.104:3306/mybatis"
userId="root" password="root">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL
和 NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成model模型,对应的包路径,以及文件存放路径(targetProject),targetProject可以指定具体的路径,如./src/main/java,
也可以使用“MAVEN”来自动生成,这样生成的代码会在target/generatord-source目录下 -->
<!--<javaModelGenerator targetPackage="com.joey.mybaties.test.pojo" targetProject="MAVEN"> -->
<javaModelGenerator targetPackage="com.demo.mybatis.pojo"
targetProject="./src/main/java">
<property name="enableSubPackages" value="true" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--对应的mapper.xml文件 -->
<sqlMapGenerator targetPackage="mappers"
targetProject="./src/main/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 对应的Mapper接口类文件 XMLMAPPER/ANNOTATEDMAPPER-->
<javaClientGenerator type="ANNOTATEDMAPPER"
targetPackage="com.demo.mybatis.mapper" targetProject="./src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 列出要生成代码的所有表,这里配置的是不生成Example文件 -->
<table tableName="food" domainObjectName="Food"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
<property name="useActualColumnNames" value="false" />
</table>
<table tableName="user" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
<property name="useActualColumnNames" value="false" />
</table>
</context>
</generatorConfiguration>
这些文件创建好之后,进入你的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,感觉这种不好使,是在另个参数里面配置的。
<!-- 对应的Mapper接口类文件 XMLMAPPER/ANNOTATEDMAPPER-->
<javaClientGenerator type="ANNOTATEDMAPPER"
targetPackage="com.demo.mybatis.mapper" targetProject="./src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
选择XMLMAPPER(xml文件形式)生成的如下:
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
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 注入,代替作用
搞定:)
接下来进行重要特性了解与源码分析:)