1. Mybatis一些底层
(一)通过输入流读取Mybatis配置文件
//1.通过输入流读取Mybatis配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
这一步仅仅创建了一个输入流读取配置文件内容
(二)获取SqlSessionFactory
//2.获取SqlSessionFactory(使用构建者设计模式)
/*
* 1.创建事务
* 2.创建数据源
* 3.解析sql
* */
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
在底层中有一个很重要的属性 configuration配置对象
以后会将很多从xml文件中解析出来的属性放到configuration配置对象里
在底层中通过XMLConfigBuilder解析xml,使用dom解析配合xpath可以直接找到节点对象
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
根据获取到的configuration节点获取其子节点
private void parseConfiguration(XNode root) {
try {
// issue #117 read properties first
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
loadCustomLogImpl(settings);
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
typeHandlerElement(root.evalNode("typeHandlers"));
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
在configuration的子节点中有以下三个重要的节点:
1.properties节点 处理db.properties 将key-value放入configration对象
public static Properties getResourceAsProperties(String resource) throws IOException {
Properties props = new Properties();
try (InputStream in = getResourceAsStream(resource)) {
//resource就是db.properties
props.load(in);//将db.properties中的key-value存储起来
}
return props;
}
2.envirments节点 创建事务工厂和数据源并放入configration对象
private void environmentsElement(XNode context) throws Exception {
if (context != null) {
if (environment == null) {
environment = context.getStringAttribute("default");
}
for (XNode child : context.getChildren()) {
String id = child.getStringAttribute("id");
if (isSpecifiedEnvironment(id)) {
//创建事务工厂
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
//创建数据源工厂
DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
//根据数据源工厂获得数据源对象
DataSource dataSource = dsFactory.getDataSource();
Environment.Builder environmentBuilder = new Environment.Builder(id)
.transactionFactory(txFactory)
.dataSource(dataSource);
//将事务工厂与数据源对象放入configuration对象中
configuration.setEnvironment(environmentBuilder.build());
break;
}
}
}
}
3.mappers namespace+id sql语句
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");
//根据mapper中的属性获得对应的mapper.xml的信息并解析
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
try(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);
try(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.");
}
}
}
}
}
private void configurationElement(XNode context) {
try {
//获得namespace
String namespace = context.getStringAttribute("namespace");
if (namespace == null || namespace.isEmpty()) {
throw new BuilderException("Mapper's namespace cannot be empty");
}
//将namespace设置进builderAssistant对象中
builderAssistant.setCurrentNamespace(namespace);
cacheRefElement(context.evalNode("cache-ref"));
cacheElement(context.evalNode("cache"));
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
resultMapElements(context.evalNodes("/mapper/resultMap"));
sqlElement(context.evalNodes("/mapper/sql"));
//根据标签获得sql语句的增删改查类型
buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
} catch (Exception e) {
throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
}
}
public void parseStatementNode() {
//获取节点的id属性值
String id = context.getStringAttribute("id");
String databaseId = context.getStringAttribute("databaseId");
if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
return;
}
//获得节点对象的名字(也就是增删改查)并大写
String nodeName = context.getNode().getNodeName();
SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
boolean useCache = context.getBooleanAttribute("useCache", isSelect);
boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);
// Include Fragments before parsing
XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
includeParser.applyIncludes(context.getNode());
String parameterType = context.getStringAttribute("parameterType");
Class<?> parameterTypeClass = resolveClass(parameterType);
String lang = context.getStringAttribute("lang");
LanguageDriver langDriver = getLanguageDriver(lang);
// Parse selectKey after includes and remove them.
processSelectKeyNodes(id, parameterTypeClass, langDriver);
// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
KeyGenerator keyGenerator;
String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
if (configuration.hasKeyGenerator(keyStatementId)) {
keyGenerator = configuration.getKeyGenerator(keyStatementId);
} else {
keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
}
//sqlSource 中存放了sql语句
SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
Integer fetchSize = context.getIntAttribute("fetchSize");
Integer timeout = context.getIntAttribute("timeout");
String parameterMap = context.getStringAttribute("parameterMap");
String resultType = context.getStringAttribute("resultType");
Class<?> resultTypeClass = resolveClass(resultType);
//获取到resultMap属性的值
String resultMap = context.getStringAttribute("resultMap");
String resultSetType = context.getStringAttribute("resultSetType");
ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
if (resultSetTypeEnum == null) {
resultSetTypeEnum = configuration.getDefaultResultSetType();
}
String keyProperty = context.getStringAttribute("keyProperty");
String keyColumn = context.getStringAttribute("keyColumn");
String resultSets = context.getStringAttribute("resultSets");
//将从标签中获得的数据存入builderAssistant对象中
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
public String applyCurrentNamespace(String base, boolean isReference) {
if (base == null) {
return null;
}
if (isReference) {
// is it qualified with any namespace yet?
if (base.contains(".")) {
return base;
}
} else {
// is it qualified with this namespace yet?
if (base.startsWith(currentNamespace + ".")) {
return base;
}
if (base.contains(".")) {
throw new BuilderException("Dots are not allowed in element names, please remove it from " + base);
}
}
//返回namespace+id
return currentNamespace + "." + base;
}
(三)获取SqlSession
//3.获取SqlSession
/*
* 封装了
* 1.增删改查的操作
* 2.事务操作
* 3.ORM映射
* */
SqlSession sqlSession = sqlSessionFactory.openSession();
(四)执行增删改查并返回结果(除了查询还要提交事务)
(五)资源释放
//5.资源释放
sqlSession.close();
2.别名 Alias
(一)明确指定别名
通过<typeAlias>
标签明确设置类型的别名。
-
type:类型全限定路径。
-
alias:别名名称。
<typeAliases>
<typeAlias type="" alias=""></typeAlias>
</typeAliases>
1. 如果需要给多个类型定义别名,需要编写多个<typeAlias>
标签。
2. 如果需要给一个类定义多个别名,需要编写多个<typeAlias>
标签。
3.一个类可以有多个别名
4.设置别名后,类的全限定路径依然可以使用。
5.明确配置别名时不区分大小写
(二)指定包中所有类的别名
<typeAliases>
<!-- 指定包 -->
<package name=""/>
</typeAliases>
1.一个类可以有多个别名。
2.明确指定别名和指定包的方式可以同时存在。
3.在使用<package>
定义别名时,严格区分大小写。
(三)MyBatis内置别名
别名 | 映射的类型 | 别名 | 映射的类型 | 别名 | 映射的类型 | ||
---|---|---|---|---|---|---|---|
_byte | byte | string | String | date | Date | ||
_long | long | byte | Byte | decimal | BigDecimal | ||
_short | short | long | Long | bigdecimal | BigDecimal | ||
_int | int | short | Short | object | Object | ||
_integer | int | int | Integer | map | Map | ||
_double | double | integer | Integer | hashmap | HashMap | ||
_float | float | double | Double | list | List | ||
_boolean | boolean | float | Float | arraylist | ArrayList | ||
boolean | Boolean | collection | Collection | ||||
iterator | Iterator |
3.SQL查询结果填充的几种方式(面试题)
(一)Auto Mapping
保证数据库中列名和属性名相同,就可以自动进行映射。
也可以给列起别名,让别名和属性名对应。对应时不用区分大小写。
(二)resultMap
在映射文件中不在使用resultType属性
<?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="a.b.c">
<!-- type:数据库中每行数据对应的实体类型,支持别名 -->
<!-- id:自定义名称-->
<resultMap id="myid" type="People2">
<!-- id标签定义主键列和属性的映射关系关系 -->
<!-- property 类中属性名称,区分大小写-->
<!-- column 表中列名-->
<id property="peoId" column="peo_id"/>
<!-- result标签定义非主键列和属性的映射关系-->
<result property="peoName" column="peo_name"/>
</resultMap>
<!-- resultMap的值必须和resultMap的id相同 -->
<select id="myid" resultMap="myid">
select * from tb_people
</select>
</mapper>
(三)驼峰转换
在MySQL中列名命名规范是xxx_yyy,多个单词之间使用下划线进行分割。在Java中属性命名规范是xxxYyy,小驼峰的方式进行命名。这两种技术的命名习惯是不一样的,这就导致每次都需要手动配置映射关系。
<settings>
<!-- 开启驼峰转换 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
4.接口绑定方案
MyBatis提供了也提供了一种接口绑定方案,通过SqlSession的getMapper方法产生接口的动态代理对象。然后通过对象调用接口中提供的功能。
流程:
(一) 创建项目并配置pom.xml
(二)创建全局配置文件
在resources中创建mybatis-config.xml。
<mappers>
<!-- 方式一:单独指定 mapper接口 -->
<!-- 指定mapper接口的路径 -->
<mapper class=" "/>
<!-- 方式二:指定 mapper接口的包 -->
<!-- 此处换为package,里面写接口和映射文件所在的包 -->
<package name=""/>
</mappers>
(三)创建实体类、接口
(四)创建映射文件
<?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">
<!-- 1.mapper接口和对应的映射文件完成绑定,mybatis自动创建mapper接口的实现类。-->
<!-- 2.映射文件中的sql和接口中的方法完成绑定。-->
<!-- 要求:-->
<!-- 1.接口名 和 映射文件名相同-->
<!-- 2.接口编译后的输出目录和映射文件输出目录相同-->
<!-- 1.将映射文件放到接口的mapper包中(配置资源拷贝)-->
<!-- 2.在resources中创建和mapper接口相同的目录-->
<!-- 1.namespace:包名.接口名 -->
<!-- 2.sql标签的id和接口中方法名相同 -->
<!-- 3.sql标签的返回值类型和接口的返回值类型相同,如集合类型,指定为集合的泛型 -->
<mapper namespace="">
<select id="" resultType="">
</select>
</mapper>
(五)添加资源拷贝插件
由于映射文件添加到了com.bjsxt.mapper包中,所以需要添加资源拷贝插件,保证映射文件能被编译。
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
(六)编写测试类
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlsession = sqlSessionFactory .openSession();
// getMapper方法采用了动态代理模式,创建接口的代理对象
PeopleMapper peopleMapper = sqlsession .getMapper(PeopleMapper.class);
List<People> list = peopleMapper.selectAll();
System.out.println(list);
session.close();
}
}