MyBatis的内容介绍

1简介

.......................................................................................................................................

1.1简介

1.1.1什么是MyBatis?

MyBatis是一个一级持久性框架,支持自定义SQL和存储过程以及高级映射。MyBatis几乎消除了所有JDBC代码和手动设置

参数和结果检索。MyBatis可以使用简单的XML或注释进行配置并将原语、接口和javapojo(普通的旧Java对象)映射到数据库记录。

1.1.2帮助改进此文档…

如果您发现此文档以任何方式缺少,或者缺少某个功能的文档,则最好的办法是了解它,然后自己写文档!

2开始

.......................................................................................................................................

2.1开始

2.1.1安装

要使用MyBatis,只需要在类路径中包含MyBatis-x.x.x.jar文件。如果您使用的是Maven,只需将以下依赖项添加到pom.xml中:

<dependency>
       <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
       <version>x.x.x</version>
</dependency>
 

2.1.2从XML构建SqlSessionFactory

每个MyBatis应用程序都围绕一个SqlSessionFactory实例。一个SqlSessionFactory实例可以通过使用SqlSessionFactoryBuilder获取。SqlSessionFactoryBuilder可以生成XML配置文件中的SqlSessionFactory实例,或来自配置类。从XML文件构建SqlSessionFactory实例非常简单。建议您对此配置使用类路径资源,但可以使用任何InputStream实例,包括从文本文件路径或file://URL创建的文件。MyBatis包含一个名为Resources的实用类,它包含许多方法,使从类路径和其他位置。

    String resource = "org/mybatis/example/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

配置XML文件包含MyBatis系统核心的设置,包括用于获取数据库连接实例的数据源,以确定事务的范围和控制方式。XML的全部细节配置文件可以在本文档后面找到,下面是一个简单的示例:

<?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="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>

尽管XML配置文件还有很多内容,但上面的示例指出了最关键的部分。注意XML头,它是验证XML文档所必需的。环境的主体元素包含用于事务管理和连接池的环境配置。mappers元素包含一个映射器列表——XML文件和/或带注释的Java接口包含SQL代码和映射定义的类

2.1.3构建没有XML的SqlSessionFactory

如果您希望直接从Java而不是XML构建配置,或者创建自己的配置配置生成器MyBatis提供了一个完整的配置类,它提供了配置选项作为XML文件。

DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
 

注意,在本例中,配置正在添加映射器类。映射器类是包含SQL映射注释的Java类,这些注释避免了XML的需要。但是,由于Java注释的一些限制和MyBatis映射的复杂性,对于最高级的映射(如嵌套连接映射)仍然需要XML映射。因此,如果存在对等XML文件,MyBatis将自动查找并加载该文件(在本例中,将基于BlogMapper.class的类路径和名称加载BlogMapper.XML)。稍后再谈。

2.1.4从SqlSessionFactory获取SqlSession

现在已经有了SqlSessionFactory,顾名思义,您可以获取SqlSession的一个实例。SqlSession包含对数据库执行SQL命令所需的所有方法。可以直接对SqlSession实例执行映射的SQL语句。例如:

SqlSession session = sqlSessionFactory.openSession();

try {  Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101); }

finally { session.close(); }

虽然这种方法有效,而且以前版本MyBatis的用户也很熟悉,但现在有了一种更干净的方法。使用正确描述给定语句的参数和返回值的接口(例如BlogMapper.class),您现在可以执行更干净、更类型安全的代码,而不需要易出错的字符串文本和转换。

SqlSession session = sqlSessionFactory.openSession();

try { BlogMapper mapper = session.getMapper(BlogMapper.class);Blog blog = mapper.selectBlog(101); }

finally { session.close();}

现在让我们来探究一下这里到底在执行什么。

2.1.5探索映射SQL语句

此时,您可能想知道SqlSession或Mapper类到底在执行什么。映射SQL语句的主题是一个很大的主题,这个主题很可能会主导本文档的大部分内容。但是为了让你知道到底在运行什么,这里有几个例子。

在上面的任何一个示例中,语句都可以由XML或注释定义。我们先来看看XML。MyBatis提供的全套功能可以通过使用基于XML的映射语言来实现,这种语言多年来使MyBatis很受欢迎。如果您以前使用过MyBatis,那么您将熟悉这个概念,但是对XML映射文档有许多改进,这些改进将在以后变得清晰。下面是一个基于XML的映射语句的示例,它将满足上述SqlSession调用。

<?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="org.mybatis.example.BlogMapper">

         <select id="selectBlog" resultType="Blog">

                select * from Blog where id = #{id}

          </select>

</mapper>

虽然对于这个简单的例子来说这看起来有很多开销,但实际上它非常轻。您可以在一个mapper XML文件中定义任意多个映射语句,这样就可以从XML头和doctype声明中获得很多好处。文件的其余部分是非常不言而喻的。它在名称空间“org.mybatis.example.BlogMapper”中为映射语句“selectBlog”定义了一个名称,您可以通过指定“org.mybatis.example.BlogMapper.selectBlog”的完全限定名来调用它,如我们在下面的示例中所做的那样:

Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);

注意这与在完全限定的Java类上调用方法有多相似,这是有原因的。此名称可以直接映射到与命名空间同名的映射器类,方法与映射的select语句的名称、参数和返回类型匹配。这使您可以非常简单地对映射器接口调用方法,如您在上面所看到的,但在下面的示例中它仍然是这样:

BlogMapper mapper = session.getMapper(BlogMapper.class);Blog blog = mapper.selectBlog(101);

第二种方法有很多优点。首先,它不依赖于字符串文字,所以更安全。其次,如果IDE有代码完成,那么在导航映射的SQL语句时可以利用它。

注意关于名称空间的注释。

命名空间在以前的MyBatis版本中是可选的,这是令人困惑和无助的。名称空间现在是必需的,其目的不仅仅是用更长的、完全限定的名称隔离语句。

正如您在这里看到的,名称空间支持接口绑定,即使您认为今天不会使用它们,您也应该遵循这里列出的这些实践,以防您改变主意。只使用一次名称空间,并将其放在适当的Java包名称空间中,从长远来看,将清理代码并提高MyBatis的可用性。

名称解析:为了减少键入的数量,MyBatis对所有命名的配置元素(包括语句、结果映射、缓存等)使用以下名称解析规则。

•直接查找完全限定名(例如“com.mypackage.MyMapper.selectAllThings”),如果找到则使用。

•短名称(例如“selectAllThings”)可用于引用任何明确的条目。但是,如果有两个或多个(例如“com.foo.selectAllThings和com.bar.selectAllThings”),则会收到错误报告,指出短名称不明确,因此必须完全限定。像BlogMapper这样的Mapper类还有一个技巧。它们的映射语句根本不需要用XML映射。相反,他们可以使用Java注释。例如,可以删除上面的XML并替换为:

package org.mybatis.example; public interface BlogMapper { @Select("SELECT * FROM blog WHERE id = #{id}")Blog selectBlog(int id);}

2.1.6范围和生命周期

了解到目前为止我们讨论过的各种作用域和生命周期类非常重要。不正确地使用它们会导致严重的并发问题。

注意对象生命周期和依赖注入框架

依赖注入框架可以创建线程安全的、事务性的SqlSessions和映射器,并将它们直接注入到bean中,这样您就可以忘记它们的生命周期。您可能希望查看MyBatis Spring或MyBatis Guice子项目,以了解有关在DI框架中使用MyBatis的更多信息。

2.1.6.1 SqlSessionFactoryBuilder版本

这个类可以被实例化、使用和丢弃。一旦创建了SqlSessionFactory,就不需要保留它。因此,SqlSessionFactoryBuilder实例的最佳作用域是方法作用域(即本地方法变量)。您可以重用SqlSessionFactoryBuilder来构建多个SqlSessionFactory实例,但最好还是不要保留它,以确保所有的XML解析资源都被释放出来用于更重要的事情。

2.1.6.2 SQL会话工厂

创建之后,SqlSessionFactory应该在应用程序执行期间存在。应该没有或几乎没有理由处置或重建它。最好不要在应用程序运行中多次重建SqlSessionFactory。这样做应该被认为是一种“臭味”。因此,SqlSessionFactory的最佳作用域是application作用域。这可以通过多种方式实现。最简单的方法是使用单例模式或静态单例模式。

2.1.6.3 SQL会话

每个线程都应该有自己的SqlSession实例。SqlSession的实例不能共享,并且不是线程安全的。因此,最好的作用域是请求或方法作用域。永远不要在静态字段甚至类的实例字段中保留对SqlSession实例的引用。永远不要在任何托管范围(如Servlet框架的HttpSession)中保留对SqlSession的引用。如果您正在使用任何类型的web框架,请考虑SqlSession遵循与HTTP请求类似的范围。换句话说,在接收到HTTP请求时,可以打开SqlSession,然后在返回响应时,可以关闭它。结束会议非常重要。您应该始终确保它在finally块内关闭。以下是确保关闭SqlSessions的标准模式:

SqlSession session = sqlSessionFactory.openSession();

try { // do work }

finally { session.close(); }

在代码中始终使用此模式将确保正确关闭所有数据库资源。

2.1.6.4映射程序实例

映射器是创建用来绑定到映射语句的接口。映射器接口的实例是从SqlSession获取的。因此,从技术上讲,任何映射器实例的最广泛范围都与从中请求它们的SqlSession相同。但是,映射器实例的最佳作用域是方法作用域。也就是说,应该在使用它们的方法中请求它们,然后丢弃它们。它们不需要显式关闭。与SqlSession类似,在整个请求过程中保留它们并不是一个问题,但您可能会发现,在这个级别管理太多资源将很快失控。保持简单,将映射器保持在方法范围内。下面的示例演示了这种做法

SqlSession session = sqlSessionFactory.openSession();

try { BlogMapper mapper=session.getMapper(BlogMapper.class);// do work }

finally { session.close();}

3配置XML

3.1配置

MyBatis配置包含对MyBatis行为有显著影响的设置和属性。文件的高层结构如下:

• configuration

• properties

• settings

• typeAliases(类型别名)

• typeHandlers

• objectFactory

• plugins

• environments

• environment

• transactionManager

• dataSource

• databaseIdProvider

• mappers

3.1.1特性

这些是可外部化的、可替换的属性,可以在典型的Java属性文件实例中配置,也可以通过properties元素的子元素传入。例如:

<properties resource="org/mybatis/example/config.properties">

               <property name="username" value="dev_user"/>

                 <property name="password" value="pwd"/>

</properties>

然后,可以在整个配置文件中使用这些属性来替换需要动态配置的值。例如:

<dataSource type="POOLED">

<property name="driver" value="${driver}"/>

<property name="url" value="${url}"/>

<property name="username" value="${username}"/>

<property name="password" value="${password}"/>

</dataSource>

本例中的用户名和密码将替换为properties元素中设置的值。驱动程序和url属性将替换为config.properties文件中包含的值。这为配置提供了很多选项。属性也可以传递到SqlSessionFactoryBuilder.build()方法中。例如:

SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, props); // ... or ...

SqlSessionFactory factory = new SqlSessionFactoryBuilder.build(reader, environment, props);

如果一个属性存在于这些位置中的多个位置,MyBatis将按以下顺序加载它们:

•首先读取Properties元素主体中指定的属性,

•第二次读取从类路径资源或Properties元素的url属性加载的属性,并覆盖已指定的任何重复属性,

•最后读取作为方法参数传递的属性,并覆盖从属性主体和资源/url属性加载的任何重复属性。

因此,最高优先级的属性是作为方法参数传入的属性,然后是资源/url属性,最后是properties元素主体中指定的属性。

由于MyBatis3.4.2,您可以按如下方式在占位符中指定默认值:

<dataSource type="POOLED">

           <property name="username" value="${username:ut_user}"/>               <!--如果“用户名”属性-->

</dataSource>

默认情况下禁用此功能。如果在占位符中指定默认值,则应通过添加以下特殊属性来启用此功能:

<properties resource=“org/mybatis/example/config.properties”>

          <property name="org.apache.ibatis.parsing.PropertyParser.enable-default-value" val

</properties>

另外请注意,如果已经使用“:”作为属性键(例如db:username),或者已经使用OGNL表达式的三元运算符(例如${tableName!=null?tableName:'global_constants'})在sql定义中,应该通过添加一个特殊属性来更改分隔键和默认值的字符,如下所示:

<properties resource="org/mybatis/example/config.properties">

                    <property name="org.apache.ibatis.parsing.PropertyParser.default-value-separator"

</properties>

<dataSource type="POOLED">

<!-- ... -->

<property name="username" value="${db:username?:ut_user}"/>

</dataSource>

3.1.2设置

这些是非常重要的调整,可以修改MyBatis在运行时的行为方式。下表介绍了这些设置及其含义和默认值。

Setting

Description

Valid Values

Default

cacheEnabled

Globally enables or disables any caches configured in any mapper under this configuration.

true | false

true

lazyLoadingEnabled

Globally enables or disables lazy loading. When enabled, all

relations will be lazily loaded. This value can be superseded for an specific relation by using the fetchType attribute on it.

true | false

false

aggressiveLazyLoading

When enabled, any

method call will load all the lazy properties of the object. Otherwise, each property is loaded on demand (see also

lazyLoadTriggerMet

true | false

hods).

false (true in ≤3.4.1)

multipleResultSetsEnabled

Allows or disallows multiple ResultSets to be returned from a single statement (compatible driver required).

true | false

true

useColumnLabel

Uses the column label instead of the column name. Different drivers behave differently in this respect. Refer to the driver documentation, or test out both modes to determine how your driver behaves.

true | false

true

useGeneratedKeys

Allows JDBC support for generated keys. A compatible driver is required. This setting forces generated keys to be used if set to true, as some drivers deny compatibility but still work (e.g. Derby).

true | false

False

 

autoMappingBehavior Specifies if and NONE, PARTIAL, FULL PARTIAL

how MyBatis should automatically map columns to fields/ properties. NONE disables auto-mapping. PARTIAL will only automap results with no nested result mappings defined inside. FULL will auto-map result mappings of any complexity (containing nested or otherwise).

autoMappingUnknownColumnBehaviorSpecify the behavior NONE, WARNING, NONE

                                                  when detects an FAILING

unknown column (or unknown property type) of automatic mapping target.

• NONE: Do nothing

• WARNING: Output warning log

(The log level of

'org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' must be set to WARN)

• FAILING: Fail mapping (Throw

SqlSessionException)

defaultExecutorType Configures the default SIMPLE REUSE BATCH SIMPLE

executor. SIMPLE executor does nothing special. REUSE executor reuses prepared statements. BATCH executor reuses statements and batches updates.

defaultStatementTimeout Sets the number of Any positive integer Not Set (null)

seconds the driver will wait for a response from the database.

defaultFetchSize Sets the driver a hint as Any positive integer Not Set (null)

to control fetching size for return results. This parameter value can be override by a query setting.

safeRowBoundsEnabled Allows using RowBounds true | false False

on nested statements. If allow, set the false.

safeResultHandlerEnabled Allows using true | false True

ResultHandler on nested statements. If allow, set the false.

mapUnderscoreToCamelCase

Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn.

true | false

False

localCacheScope

MyBatis uses local cache to prevent circular references and speed up repeated nested queries. By default (SESSION) all queries executed during a session are cached. If

localCacheScope=STATEM

local session will be used just for statement execution, no data will be shared between two different calls to the same SqlSession.

SESSION | STATEMENT

ENT

SESSION

jdbcTypeForNull

Specifies the JDBC type for null values when no specific JDBC type was provided for the parameter. Some drivers require specifying the column JDBC type but others work with generic values like NULL, VARCHAR or OTHER.

JdbcType enumeration.

Most common are: NULL,

VARCHAR and OTHER

OTHER

lazyLoadTriggerMethods

Specifies which Object's methods trigger a lazy load

A method name list separated by commas

equals,clone,hashCode,toString

defaultScriptingLanguage

Specifies the language used by default for dynamic SQL generation.

A type alias or fully qualified class name.

 

defaultEnumTypeHandler

Specifies the

TypeHandler used by default for Enum. (Since:

3.4.5)

A type alias or fully qualified class name.

 

callSettersOnNulls

Specifies if setters or map's put method will be called when a retrieved value is null. It is useful when you rely on Map.keySet() or null value initialization. Note primitives such as (int,boolean,etc.) will not be set to null.

true | false

false

org.apache.ibatis.scripting.xmltags.XMLLangu

org.apache.ibatis.type.EnumTypeHandler

returnInstanceForEmptyRow

MyBatis, by default, returns null when all the columns of a returned row are NULL. When this setting is enabled, MyBatis returns an empty instance instead. Note that it is also applied to nested results (i.e. collectioin and association). Since: 3.4.2

true | false

false

logPrefix

Specifies the prefix string that MyBatis will add to the logger names.

Any String

Not set

logImpl

Specifies which logging implementation MyBatis should use. If this setting is not present logging implementation will be autodiscovered.

SLF4J | LOG4J | LOG4J2

| JDK_LOGGING |

COMMONS_LOGGING

| STDOUT_LOGGING |

NO_LOGGING

Not set

proxyFactory

Specifies the proxy tool that MyBatis will use for creating lazy loading capable objects.

CGLIB | JAVASSIST

JAVASSIST (MyBatis 3.3 or above)

vfsImpl

Specifies VFS implementations

Fully qualified class names of custom VFS implementation separated by commas.

Not set

useActualParamName

Allow referencing statement parameters by their actual names declared in the method signature. To use this feature, your project must be compiled in Java 8 with -parameters

option. (Since: 3.4.1)

true | false

true

configurationFactory

Specifies the class that provides an instance of

Configuration. The returned Configuration instance is used to load lazy properties of deserialized objects. This class must have a method with a signature static

Configuration getConfiguration().

(Since: 3.2.3)

A type alias or fully qualified class name.

未完待续

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值