MyBatis
来源:互联网 发布:钉钉软件使用手册 编辑:程序博客网 时间:2024/05/02 00:26
XML 映射配置文件
MyBatis 的 XML 配置文件包含了影响 MyBatis 行为甚深的设置和属性信息。XML 文档的高层级结构如下:
- configuration 配置
- properties 属性
- settings 设置
- typeAliases 类型命名
- typeHandlers 类型处理器
- objectFactory 对象工厂
- plugins 插件
- environments 环境
- environment 环境变量
- transactionManager 事务管理器
- dataSource 数据源
- environment 环境变量
- databaseIdProvider chinese?
- mappers 映射器
properties
这些是外部化的,可替代的属性,这些属性也可以配置在典型的 Java 属性配置文件中,或者通过 properties 元素的子元素来传递。例如:
<properties resource="org/mybatis/example/config.properties"> <property name="username" value="dev_user"/> <property name="password" value="F2Fa3!33TYyg"/></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>
这个例子中的 username 和 password 将会由 properties 元素中设置的值来替换。driver 和url 属性将会从包含进来的 config.properties 文件中的值来替换。这里提供很多配置的选项。
属性也可以被传递到 SqlSessionBuilder.build()方法中。例如:
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, props);// ... or ...SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, environment, props);
如果在这些地方,属性多于一个的话,MyBatis 按照如下的顺序加载它们:
- 在 properties 元素体内指定的属性首先被读取。
- 从类路径下资源或 properties 元素的 url 属性中加载的属性第二被读取,它会覆盖已经存在的完全一样的属性。
- 作为方法参数传递的属性最后被读取,它也会覆盖任一已经存在的完全一样的属性,这些属性可能是从 properties 元素体内和资源/url 属性中加载的。
因此,最高优先级的属性是那些作为方法参数的,然后是资源/url 属性,最后是 properties元素中指定的属性。
settings
这些是极其重要的调整,它们会修改 MyBatis 在运行时的行为方式。下面这个表格描述了设置信息,它们的含义和默认值。
一个设置信息元素的示例,完全的配置如下所示:
<settings> <setting name="cacheEnabled" value="true"/> <setting name="lazyLoadingEnabled" value="true"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="useGeneratedKeys" value="false"/> <setting name="autoMappingBehavior" value="PARTIAL"/> <setting name="defaultExecutorType" value="SIMPLE"/> <setting name="defaultStatementTimeout" value="25"/> <setting name="safeRowBoundsEnabled" value="false"/> <setting name="mapUnderscoreToCamelCase" value="false"/> <setting name="localCacheScope" value="SESSION"/> <setting name="jdbcTypeForNull" value="OTHER"/> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/></settings>
typeAliases
类型别名是为 Java 类型命名一个短的名字。它只和 XML 配置有关,只用来减少类完全限定名的多余部分。例如:
<typeAliases> <typeAlias alias="Author" type="domain.blog.Author"/> <typeAlias alias="Blog" type="domain.blog.Blog"/> <typeAlias alias="Comment" type="domain.blog.Comment"/> <typeAlias alias="Post" type="domain.blog.Post"/> <typeAlias alias="Section" type="domain.blog.Section"/> <typeAlias alias="Tag" type="domain.blog.Tag"/></typeAliases>
使用这个配置,“Blog”可以任意用来替代“domain.blog. Blog”所使用的地方。
You can also specify a package where MyBatis will search for beans. For example:
<typeAliases> <package name="domain.blog"/></typeAliases>
Each bean found in domain.blog , if no annotation is found, will be registered as an alias using uncapitalized non-qualified class name of the bean. Thas isdomain.blog.Author will be registered asAuthor . If the @Alias annotation is found its value will be used as an alias. See the example below:
@Alias("author")public class Author { ...}
对于普通的 Java 类型,有许多内建的类型别名。它们都是大小写不敏感的,由于重载的名字,要注意原生类型的特殊处理。
typeHandlers
无论是 MyBatis 在预处理语句中设置一个参数,还是从结果集中取出一个值时,类型处理器被用来将获取的值以合适的方式转换成 Java 类型。下面这个表格描述了默认的类型处理器。
你可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。 //TODO translation needed To do so, simply extend theorg.apache.ibatis.type.BaseTypeHandler class and optionally map your newTypeHandler class to a JDBC type. 例如:
// ExampleTypeHandler.java@MappedJdbcTypes(JdbcType.VARCHAR)public class ExampleTypeHandler extends BaseTypeHandler<String> { @Override public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, parameter); } @Override public String getNullableResult(ResultSet rs, String columnName) throws SQLException { return rs.getString(columnName); } @Override public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return rs.getString(columnIndex); } @Override public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return cs.getString(columnIndex); }}
<!-- mybatis-config.xml --><typeHandlers> <typeHandler handler="org.mybatis.example.ExampleTypeHandler"/></typeHandlers>
使用这样的类型处理器将会覆盖已经存在的处理 Java 的 String 类型属性和 VARCHAR参数及结果的类型处理器。要注意 MyBatis 不会审视数据库元信息来决定使用哪种类型,所以你必须在参数和结果映射中指定那是 VARCHAR 类型的字段,来绑定到正确的类型处理器上。这是因为 MyBatis 直到语句被执行都不知道数据类型的这个现实导致的。
// TODO translation needed MyBatis will know the the Java type that you want to handle with this TypeHandler by introspecting its generic type, but you can override this behavior by two means:
- Adding a javaType attribute to the typeHandler element (for example:javaType="String")
- Adding a @MappedTypes annotation to your TypeHandler class specifying the list of java types to associate it with. This annotation will be ignored if thejavaType attribute as also been specified.
Associated JDBC type can be specified by two means:
- Adding a jdbcType attribute to the typeHandler element (for example:jdbcType=VARCHAR).
- Adding a @MappedJdbcTypes annotation to your TypeHandler class specifying the list of JDBC types to associate it with. This annotation will be ignored if thejdbcType attribute as also been specified.
And finally you can let MyBatis search for your TypeHandlers:
<!-- mybatis-config.xml --><typeHandlers> <package name="org.mybatis.example"/></typeHandlers>
Note that when using the autodiscovery feature JDBC types can only be specified with annotations.
You can create a generic TypeHandler that is able to handle more than one class. For that purpose add a constructor that receives the class as a parameter and MyBatis will pass the actual class when constructing the TypeHandler.
//GenericTypeHandler.javapublic class GenericTypeHandler<E extends MyObject> extends BaseTypeHandler<E> { private Class<E> type; public GenericTypeHandler(Class<E> type) { if (type == null) throw new IllegalArgumentException("Type argument cannot be null"); this.type = type; } ...
EnumTypeHandler and EnumOrdinalTypeHandler are generic TypeHandlers. We will learn about them in the following section.
Handling Enums
If you want to map an Enum, you'll need to use either EnumTypeHandler orEnumOrdinalTypeHandler.
For example, let's say that we need to store the rounding mode that should be used with some number if it needs to be rounded. By default, MyBatis usesEnumTypeHandler to convert theEnum values to their names.
Note EnumTypeHandler is special in the sense that unlike other handlers, it does not handle just one specific class, but any class that extendsEnumHowever, we may not want to store names. Our DBA may insist on an integer code instead. That's just as easy: addEnumOrdinalTypeHandler to thetypeHandlers in your config file, and now eachRoundingMode will be mapped to an integer using its ordinal value.
<!-- mybatis-config.xml --><typeHandlers> <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="java.math.RoundingMode"/></typeHandlers>
But what if you want to map the same Enum to a string in one place and to integer in another?
The auto-mapper will automatically use EnumOrdinalTypeHandler, so if we want to go back to using plain old ordinaryEnumTypeHandler, we have to tell it, by explicitly setting the type handler to use for those SQL statements.
(Mapper files aren't covered until the next section, so if this is your first time reading through the documentation, you may want to skip this for now and come back to it later.)
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="org.apache.ibatis.submitted.rounding.Mapper"><resultMap type="org.apache.ibatis.submitted.rounding.User" id="usermap"><id column="id" property="id"/><result column="name" property="name"/><result column="funkyNumber" property="funkyNumber"/><result column="roundingMode" property="roundingMode"/></resultMap><select id="getUser" resultMap="usermap">select * from users</select><insert id="insert" parameterType="org.apache.ibatis.submitted.rounding.User"> insert into users (id, name, funkyNumber, roundingMode) values ( #{id}, #{name}, #{funkyNumber}, #{roundingMode} )</insert><resultMap type="org.apache.ibatis.submitted.rounding.User" id="usermap2"><id column="id" property="id"/><result column="name" property="name"/><result column="funkyNumber" property="funkyNumber"/><result column="roundingMode" property="roundingMode" typeHandler="org.apache.ibatis.type.EnumTypeHandler"/></resultMap><select id="getUser2" resultMap="usermap2">select * from users2</select><insert id="insert2" parameterType="org.apache.ibatis.submitted.rounding.User"> insert into users2 (id, name, funkyNumber, roundingMode) values ( #{id}, #{name}, #{funkyNumber}, #{roundingMode, typeHandler=org.apache.ibatis.type.EnumTypeHandler} )</insert></mapper>
Note that this forces us to use a resultMap instead of a resultType in our select statements.
objectFactory
MyBatis 每次创建结果对象新的实例时,它使用一个 ObjectFactory 实例来完成。如果参数映射存在,默认的 ObjectFactory 不比使用默认构造方法或带参数的构造方法实例化目标类做的工作多。如果你想重写默认的 ObjectFactory,你可以创建你自己的。比如:
// ExampleObjectFactory.javapublic class ExampleObjectFactory extends DefaultObjectFactory { public Object create(Class type) { return super.create(type); } public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) { return super.create(type, constructorArgTypes, constructorArgs); } public void setProperties(Properties properties) { super.setProperties(properties); }}
<!-- mybatis-config.xml --><objectFactory type="org.mybatis.example.ExampleObjectFactory"> <property name="someProperty" value="100"/></objectFactory>
ObjectFactory 接口很简单。它包含两个创建用的方法,一个是处理默认构造方法的,另外一个是处理带参数构造方法的。最终,setProperties 方法可以被用来配置 ObjectFactory。在 初 始化 你 的 ObjectFactory 实例 后 , objectFactory 元素 体 中定 义的 属 性会 被传 递 给setProperties 方法。
plugins
MyBatis 允许你在某一点拦截已映射语句执行的调用。默认情况下,MyBatis 允许使用插件来拦截方法调用:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
这些类中方法的详情可以通过查看每个方法的签名来发现 ,而且它们的源代码在MyBatis 的发行包中有。你应该理解你覆盖方法的行为,假设你所做的要比监视调用要多。如果你尝试修改或覆盖一个给定的方法,你可能会打破 MyBatis 的核心。这是低层次的类和方法,要谨慎使用插件。
使用插件是它们提供的非常简单的力量。简单实现拦截器接口,要确定你想拦截的指定签名。
// ExamplePlugin.java@Intercepts({@Signature( type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})})public class ExamplePlugin implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { return invocation.proceed(); } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) { }}
<!-- mybatis-config.xml --><plugins> <plugin interceptor="org.mybatis.example.ExamplePlugin"> <property name="someProperty" value="100"/> </plugin></plugins>
上面的插件将会拦截在 Executor 实例中所有的“update”方法调用,它也是负责低层次映射语句执行的内部对象。
NOTE 覆盖配置类
除了用插件来修改 MyBatis 核心行为之外,你也可以完全覆盖配置类。简单扩展它,然后覆盖其中的任意方法,之后传递它到 sqlSessionFactoryBuilder.build(myConfig)方法的调用。这可能会严重影响 MyBatis 的行为,所以要小心。
environments
MyBatis 可以配置多种环境。这会帮助你将 SQL 映射应用于多种数据库之中。例如,你也许为开发要设置不同的配置,测试和生产环境。或者你可能有多种生产级数据库却共享相同的模式,所以你会想对不同数据库使用相同的 SQL 映射。这种用例是很多的。
一个很重要的问题要记得:你可以配置多种环境,但你只能为每个 SqlSessionFactory实例选择一个。
所以,如果你想连接两个数据库,你需要创建两个 SqlSessionFactory 实例,每个数据库对应一个。而如果是三个数据库,你就需要三个实例,以此类推。记忆起来很简单:
- 每个数据库对应一个 SqlSessionFactory
为了明确创建哪种环境,你可以将它作为可选的参数传递给 SqlSessionFactoryBuilder。可以接受环境配置的两个方法签名是:
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, environment);SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, environment,properties);
如果环境被忽略,那么默认环境将会被加载,如下进行:
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader);SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader,properties);
环境元素定义了如何配置环境。
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"> <property name="..." value="..."/> </transactionManager> <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>
注意这里的键:
- 默认的环境 ID(比如:default=”development”)。
- 每个 environment 元素定义的环境 ID(比如:id=”development”)。
- 事务管理器的配置(比如:type=”JDBC”)。
- 数据源的配置(比如:type=”POOLED”)。
默认的环境和环境 ID 是自我解释的。你可以使用你喜欢的名称来命名,只要确定默认的要匹配其中之一。
transactionManager
在 MyBatis 中有两种事务管理器类型(也就是 type=”[JDBC|MANAGED]”):
- JDBC – 这个配置直接简单使用了 JDBC 的提交和回滚设置。它依赖于从数据源得到的连接来管理事务范围。
- MANAGED – 这个配置几乎没做什么。它从来不提交或回滚一个连接。而它会让容器来管理事务的整个生命周期(比如 Spring 或 JEE 应用服务器的上下文)默认情况下它会关闭连接。然而一些容器并不希望这样,因此如果你需要从连接中停止它,将 closeConnection 属性设置为 false。例如:
<transactionManager type="MANAGED"> <property name="closeConnection" value="false"/></transactionManager>
NOTE If you are planning to use MyBatis with Spring there is no need to configure any TransactionManager because the Spring module will set its own one overriding any previously set configuration.
这两种事务管理器都不需要任何属性。然而它们都是类型别名,要替换使用它们,你需要放置将你自己的类的完全限定名或类型别名,它们引用了你对 TransactionFactory 接口的实现类。
public interface TransactionFactory { void setProperties(Properties props); Transaction newTransaction(Connection conn); Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit); }
任何在 XML 中配置的属性在实例化之后将会被传递给 setProperties()方法。你的实现类需要创建一个事务接口的实现,这个接口也很简单:
public interface Transaction { Connection getConnection() throws SQLException; void commit() throws SQLException; void rollback() throws SQLException; void close() throws SQLException;}
使用这两个接口,你可以完全自定义 MyBatis 对事务的处理。
dataSource
dataSource 元素使用基本的 JDBC 数据源接口来配置 JDBC 连接对象的资源。
- 许多 MyBatis 的应用程序将会按示例中的例子来配置数据源。然而它并不是必须的。要知道为了方便使用延迟加载,数据源才是必须的。
有三种内建的数据源类型(也就是 type=”???”):
UNPOOLED– 这个数据源的实现是每次被请求时简单打开和关闭连接。它有一点慢,这是对简单应用程序的一个很好的选择,因为它不需要及时的可用连接。不同的数据库对这个的表现也是不一样的,所以对某些数据库来说配置数据源并不重要,这个配置也是闲置的。UNPOOLED 类型的数据源仅仅用来配置以下 5 种属性:
- driver – 这是 JDBC 驱动的 Java 类的完全限定名(如果你的驱动包含,它也不是 数据源类)。
- url – 这是数据库的 JDBC URL 地址。
- username – 登录数据库的用户名。
- password – 登录数据库的密码。
- defaultTransactionIsolationLevel – 默认的连接事务隔离级别。
作为可选项,你可以传递数据库驱动的属性。要这样做,属性的前缀是以“driver.”开头的,例如:
- driver.encoding=UTF8
这 样 就 会 传 递 以 值 “ UTF8 ” 来 传 递 属 性 “ encoding ”, 它 是 通 过DriverManager.getConnection(url,driverProperties)方法传递给数据库驱动。
POOLED – 这是 JDBC 连接对象的数据源连接池的实现,用来避免创建新的连接实例时必要的初始连接和认证时间。这是一种当前 Web 应用程序用来快速响应请求很流行的方法。
除了上述(UNPOOLED)的属性之外,还有很多属性可以用来配置 POOLED 数据源:
- poolMaximumActiveConnections – 在任意时间存在的活动(也就是正在使用)连接的数量。默认值:10
- poolMaximumIdleConnections – 任意时间存在的空闲连接数。
- poolMaximumCheckoutTime – 在被强制返回之前,池中连接被检查的时间。默认值:20000 毫秒(也就是 20 秒)
- poolTimeToWait – 这是给连接池一个打印日志状态机会的低层次设置,还有重新尝试获得连接,这些情况下往往需要很长时间为了避免连接池没有配置时静默失败)。默认值:20000 毫秒(也就是 20 秒)
- poolPingQuery – 发送到数据的侦测查询,用来验证连接是否正常工作,并且准备接受请求。默认是“NO PING QUERY SET”,这会引起许多数据库驱动连接由一个错误信息而导致失败。
- poolPingEnabled – 这是开启或禁用侦测查询。如果开启,你必须用一个合法的SQL 语句(最好是很快速的)设置 poolPingQuery 属性。默认值:false。
- poolPingConnectionsNotUsedFor – 这是用来配置 poolPingQuery 多次时间被用一次。这可以被设置匹配标准的数据库连接超时时间,来避免不必要的侦测。默认值:0(也就是所有连接每一时刻都被侦测-但仅仅当 poolPingEnabled 为 true 时适用)。
JNDI – 这个数据源的实现是为了使用如 Spring 或应用服务器这类的容器,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的引用。这个数据源配置只需要两个属性:
- initial_context – 这 个 属 性 用 来 从 初 始 上 下 文 中 寻 找 环 境 ( 也 就 是initialContext.lookup(initial——context) 。这是个可选属性,如果被忽略,那么data_source 属性将会直接以 initialContext 为背景再次寻找。
- data_source – 这是引用数据源实例位置的上下文的路径。它会以由 initial_context查询返回的环境为背景来查找,如果 initial_context 没有返回结果时,直接以初始上下文为环境来查找。
和其他数据源配置相似,它也可以通过名为“env.”的前缀直接向初始上下文发送属性。比如:
- env.encoding=UTF8
在初始化之后,这就会以值“UTF8”向初始上下文的构造方法传递名为“encoding”的属性。
databaseIdProvider
MyBatis is able to execute different statements depending on your database vendor. The multi-db vendor support is based on the mapped statementsdatabaseId attribute. MyBatis will load all statements with nodatabaseId attribute or with adatabaseId that matches the current one. If case the same statement if found with and without thedatabaseId the latter will be discarded. To enable the multi vendor support add adatabaseIdProvider to mybatis-config.xml file as follows:
<databaseIdProvider type="VENDOR" />
The VENDOR implementation databaseIdProvider sets as a databaseId the String returned byDatabaseMetaData#getDatabaseProductName(). As usually that string is too long and also, different versions of the same product return different values, so you may want to translate it to a shorter one by adding properties like follows:
<databaseIdProvider type="VENDOR"> <property name="SQL Server" value="sqlserver"/> <property name="DB2" value="db2"/> <property name="Oracle" value="oracle" /></databaseIdProvider>
When properties are provided, the VENDOR databaseIdProvider will search the property value corresponding to the first key found in the returned database product name or "null" if there is not a matching property. In this case, ifgetDatabaseProductName() returns "Oracle (DataDirect)" the databaseId will be set to "oracle".
You can build your own database provider by implementing the interface org.apache.ibatis.mapping.DatabaseIdProvider and registerin it in mybatis-config.xml:
public interface DatabaseIdProvider { void setProperties(Properties p); String getDatabaseId(DataSource dataSource) throws SQLException;}
mappers
既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要定义 SQL 映射语句了。但是,首先我们需要告诉 MyBatis 到哪里去找到这些语句。Java 在这方面没有提供一个很好的方法,所以最佳的方式是告诉 MyBatis 到哪里去找映射文件。你可以使用相对于类路径的资源引用,或者字符表示,或 url 引用的完全限定名(包括 file:///URLs)。例如:
<!-- Using classpath relative resources --><mappers> <mapper resource="org/mybatis/builder/AuthorMapper.xml"/> <mapper resource="org/mybatis/builder/BlogMapper.xml"/> <mapper resource="org/mybatis/builder/PostMapper.xml"/></mappers>
<!-- Using url fully qualified paths --><mappers> <mapper url="file:///var/mappers/AuthorMapper.xml"/> <mapper url="file:///var/mappers/BlogMapper.xml"/> <mapper url="file:///var/mappers/PostMapper.xml"/></mappers>
<!-- Using mapper interface classes --><mappers> <mapper class="org.mybatis.builder.AuthorMapper"/> <mapper class="org.mybatis.builder.BlogMapper"/> <mapper class="org.mybatis.builder.PostMapper"/></mappers>
<!-- Register all interfaces in a package as mappers --><mappers> <package name="org.mybatis.builder"/></mappers>
这些语句简单告诉了 MyBatis 去哪里找映射文件。其余的细节就是在每个 SQL 映射文件中了,下面的部分我们来讨论 SQL 映射文件。
Mapper XML 文件
MyBatis 真正的力量是在映射语句中。这里是奇迹发生的地方。对于所有的力量,SQL映射的 XML 文件是相当的简单。当然如果你将它们和对等功能的 JDBC 代码来比较,你会发现映射文件节省了大约 95%的代码量。MyBatis 的构建就是聚焦于 SQL 的,使其远离于普通的方式。
SQL 映射文件有很少的几个顶级元素(按照它们应该被定义的顺序):
- cache – 配置给定命名空间的缓存。
- cache-ref – 从其他命名空间引用缓存配置。
- resultMap – 最复杂,也是最有力量的元素,用来描述如何从数据库结果集中来加载你的对象。
parameterMap– 已经被废弃了!老式风格的参数映射。内联参数是首选,这个元素可能在将来被移除。这里不会记录。- sql – 可以重用的 SQL 块,也可以被其他语句引用。
- insert – 映射插入语句
- update – 映射更新语句
- delete – 映射删除语句
- select – 映射查询语句
下一部分将从语句本身开始来描述每个元素的细节。
select
查询语句是使用 MyBatis 时最常用的元素之一。直到你从数据库取出数据时才会发现将数据存在数据库中是多么的有价值,所以许多应用程序查询要比更改数据多的多。对于每次插入,更新或删除,那也会有很多的查询。这是 MyBatis 的一个基本原则,也是将重心和努力放到查询和结果映射的原因。对简单类别的查询元素是非常简单的。比如:
<select id="selectPerson" parameterType="int" resultType="hashmap"> SELECT * FROM PERSON WHERE ID = #{id}</select>
这个语句被称作 selectPerson,使用一个 int(或 Integer)类型的参数,并返回一个 HashMap类型的对象,其中的键是列名,值是列对应的值。
注意参数注释:
#{id}
这就告诉 MyBatis 创建一个预处理语句参数。使用 JDBC,这样的一个参数在 SQL 中会由一个“?”来标识,并被传递到一个新的预处理语句中,就像这样:
// Similar JDBC code, NOT MyBatis…String selectPerson = "SELECT * FROM PERSON WHERE ID=?";PreparedStatement ps = conn.prepareStatement(selectPerson);ps.setInt(1,id);
当然,这需要很多单独的 JDBC 的代码来提取结果并将它们映射到对象实例中,这就是MyBatis 节省你时间的地方。我们需要深入了解参数和结果映射。那些细节部分我们下面来了解。
select 元素有很多属性允许你配置,来决定每条语句的作用细节。
<select id="selectPerson" parameterType="int" parameterMap="deprecated" resultType="hashmap" resultMap="personResultMap" flushCache="false" useCache="true" timeout="10000" fetchSize="256" statementType="PREPARED" resultSetType="FORWARD_ONLY">
insert, update and delete
数据变更语句 insert,update 和 delete 在它们的实现中非常相似:
<insert id="insertAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" keyProperty="" keyColumn="" useGeneratedKeys="" timeout="20"><update id="insertAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" timeout="20"><delete id="insertAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" timeout="20">
下面就是 insert,update 和 delete 语句的示例:
<insert id="insertAuthor" parameterType="domain.blog.Author"> insert into Author (id,username,password,email,bio) values (#{id},#{username},#{password},#{email},#{bio})</insert><update id="updateAuthor" parameterType="domain.blog.Author"> update Author set username = #{username}, password = #{password}, email = #{email}, bio = #{bio} where id = #{id}</update><delete id="deleteAuthor" parameterType="int"> delete from Author where id = #{id}</delete>
如前所述,插入语句有一点多,它有一些属性和子元素用来处理主键的生成。
首先,如果你的数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server),那么你可以设置 useGeneratedKeys=”true”,而且设置 keyProperty 到你已经做好的目标属性上。例如,如果上面的 Author 表已经对 id 使用了自动生成的列类型,那么语句可以修改为:
<insert id="insertAuthor" parameterType="domain.blog.Author" useGeneratedKeys="true" keyProperty="id"> insert into Author (username,password,email,bio) values (#{username},#{password},#{email},#{bio})</insert>
MyBatis 有另外一种方法来处理数据库不支持自动生成类型,或者可能 JDBC 驱动不支持自动生成主键时的主键生成问题。
这里有一个简单(甚至很傻)的示例,它可以生成一个随机 ID(可能你不会这么做,但是这展示了 MyBatis 处理问题的灵活性,因为它并不真的关心 ID 的生成):
<insert id="insertAuthor" parameterType="domain.blog.Author"> <selectKey keyProperty="id" resultType="int" order="BEFORE"> select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1 </selectKey> insert into Author (id, username, password, email,bio, favourite_section) values (#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})</insert>
在上面的示例中,selectKey 元素将会首先运行,Author 的 id 会被设置,然后插入语句会被调用。这给你了一个简单的行为在你的数据库中来处理自动生成的主键,而不需要使你的 Java 代码变得复杂。
selectKey 元素描述如下:
<selectKey keyProperty="id" resultType="int" order="BEFORE" statementType="PREPARED">
sql
这个元素可以被用来定义可重用的 SQL 代码段,可以包含在其他语句中。比如:
<sql id="userColumns"> id,username,password </sql>
这个 SQL 片段可以被包含在其他语句中,例如:
<select id="selectUsers" parameterType="int" resultType="hashmap"> select <include refid="userColumns"/> from some_table where id = #{id}</select>
Parameters
在之前的语句中,你已经看到了一些简单参数的示例。 MyBatis 中参数是非常强大的在元素。对于简单的做法,大概 90%的情况,是不用太多的,比如:
<select id="selectUsers" parameterType="int" resultType="User"> select id, username, password from users where id = #{id}</select>
上面的这个示例说明了一个非常简单的命名参数映射。参数类型被设置为“int”,因此这个参数可以被设置成任何内容。原生的类型或简单数据类型,比如整型和没有相关属性的字符串,因此它会完全用参数来替代。然而,如果你传递了一个复杂的对象,那么 MyBatis的处理方式就会有一点不同。比如:
<insert id="insertUser" parameterType="User" > insert into users (id, username, password) values (#{id}, #{username}, #{password})</insert>
如果 User 类型的参数对象传递到了语句中, username 和 password 属性将会被查找,id、然后它们的值就被传递到预处理语句的参数中。
这点对于传递参数到语句中非常好。但是对于参数映射也有一些其他的特性。
首先,像 MyBatis 的其他部分,参数可以指定一个确定的数据类型。
#{property,javaType=int,jdbcType=NUMERIC}
像 MyBatis 的剩余部分,javaType 通常可以从参数对象中来去顶,除非对象是一个HashMap。那么 javaType 应该被确定来保证使用正确类型处理器。
注意 如果 null 被当作值来传递,对于所有可能为空的列,JDBC Type 是需要的。以可以自己通过阅读预处理语句的 setNull()方法的 JavaDocs 文档来研究这个。
为了自定义类型处理器,你可以指定一个确定的类型处理器类(或别名), 比如:
#{age,javaType=int,jdbcType=NUMERIC,typeHandler=MyTypeHandler}
尽管它看起来繁琐,但是实际上是你很少设置它们其中之一。
对于数值类型,对于决定有多少数字是相关的,有一个数值范围。
#{height,javaType=double,jdbcType=NUMERIC,numericScale=2}
最后,mode 属性允许你指定 IN,OUT 或 INOUT 参数。如果参数为 OUT 或 INOUT,参数对象属性的真实值将会被改变,就像你期望你需要你个输出参数。如果 mode 为 OUT(或 INOUT),而且 jdbcType 为 CURSOR(也就是 Oracle 的 REFCURSOR),你必须指定一个 resultMap 来映射结果集到参数类型。要注意这里的 javaType 属性是可选的,如果左边的空白是 jdbcType 的 CURSOR 类型,它会自动地被设置为结果集。
#{department, mode=OUT, jdbcType=CURSOR, javaType=ResultSet, resultMap=departmentResultMap}
MyBatis 也支持很多高级的数据类型,比如结构体,但是当注册 out 参数时你必须告诉语句类型名称。比如(再次提示,在实际中不要像这样换行):
#{middleInitial, mode=OUT, jdbcType=STRUCT, jdbcTypeName=MY_TYPE, resultMap=departmentResultMap}
尽管所有这些强大的选项很多时候你只简单指定属性名,MyBatis 会自己计算剩余的。最多的情况是你为 jdbcType 指定可能为空的列名。
#{firstName}#{middleInitial,jdbcType=VARCHAR}#{lastName}
字符串替换
默认情况下,使用#{}格式的语法会导致 MyBatis 创建预处理语句属性并以它为背景设置安全的值(比如?)。这样做很安全,很迅速也是首选做法,有时你只是想直接在 SQL 语句中插入一个不改变的字符串。比如,像 ORDER BY,你可以这样来使用:
ORDER BY ${columnName}
这里 MyBatis 不会修改或转义字符串。
重要 接受从用户输出的内容并提供给语句中不变的字符串,这样做是不安全的。这会导致潜在的 SQL 注入攻击,因此你不应该允许用户输入这些字段,或者通常自行转义并检查。
Result Maps
resultMap 元素是 MyBatis 中最重要最强大的元素。它就是让你远离 90%的需要从结果集中取出数据的 JDBC 代码的那个东西,而且在一些情形下允许你做一些 JDBC 不支持的事情。事实上,编写相似于对复杂语句联合映射这些等同的代码,也许可以跨过上千行的代码。ResultMap 的设计就是简单语句不需要明确的结果映射,而很多复杂语句确实需要描述它们的关系。
你已经看到简单映射语句的示例了,但没有明确的 resultMap。比如:
<select id="selectUsers" parameterType="int" resultType="hashmap"> select id, username, hashedPassword from some_table where id = #{id}</select>
这样一个语句简单作用于所有列被自动映射到 HashMap 的键上,这由 resultType 属性指定。这在很多情况下是有用的,但是 HashMap 不能很好描述一个领域模型。那样你的应用程序将会使用 JavaBeans 或 POJOs(Plain Old Java Objects,普通 Java 对象)来作为领域模型。MyBatis 对两者都支持。看看下面这个 JavaBean:
package com.someapp.model;public class User { private int id; private String username; private String hashedPassword; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getHashedPassword() { return hashedPassword; } public void setHashedPassword(String hashedPassword) { this.hashedPassword = hashedPassword; }}
基于 JavaBean 的规范,上面这个类有 3 个属性:id,username 和 hashedPassword。这些在 select 语句中会精确匹配到列名。
这样的一个 JavaBean 可以被映射到结果集,就像映射到 HashMap 一样简单。
<select id="selectUsers" parameterType="int" resultType="com.someapp.model.User"> select id, username, hashedPassword from some_table where id = #{id}</select>
要记住类型别名是你的伙伴。使用它们你可以不用输入类的全路径。比如:
<!-- In mybatis-config.xml file --><typeAlias type="com.someapp.model.User" alias="User"/><!-- In SQL Mapping XML file --><select id="selectUsers" parameterType="int" resultType="User"> select id, username, hashedPassword from some_table where id = #{id}</select>
这些情况下,MyBatis 会在幕后自动创建一个 ResultMap,基于属性名来映射列到JavaBean 的属性上。如果列名没有精确匹配,你可以在列名上使用 select 字句的别名(一个基本的 SQL 特性)来匹配标签。比如:
<select id="selectUsers" parameterType="int" resultType="User"> select user_id as "id", user_name as "userName", hashed_password as "hashedPassword" from some_table where id = #{id}</select>
ResultMap 最优秀的地方你已经了解了很多了,但是你还没有真正的看到一个。这些简单的示例不需要比你看到的更多东西。只是出于示例的原因,让我们来看看最后一个示例中外部的 resultMap 是什么样子的,这也是解决列名不匹配的另外一种方式。
<resultMap id="userResultMap" type="User"> <id property="id" column="user_id" /> <result property="username" column="username"/> <result property="password" column="password"/></resultMap>
引用它的语句使用 resultMap 属性就行了(注意我们去掉了 resultType 属性)。比如:
<select id="selectUsers" parameterType="int" resultMap="userResultMap"> select user_id, user_name, hashed_password from some_table where id = #{id}</select>
如果世界总是这么简单就好了。
高级结果映射
MyBatis 创建的一个想法:数据库不用永远是你想要的或需要它们是什么样的。而我们最喜欢的数据库最好是第三范式或 BCNF 模式,但它们有时不是。如果可能有一个单独的数据库映射,所有应用程序都可以使用它,这是非常好的,但有时也不是。结果映射就是MyBatis 提供处理这个问题的答案。
比如,我们如何映射下面这个语句?
<!-- Very Complex Statement --><select id="selectBlogDetails" parameterType="int" resultMap="detailedBlogResultMap"> select B.id as blog_id, B.title as blog_title, B.author_id as blog_author_id, A.id as author_id, A.username as author_username, A.password as author_password, A.email as author_email, A.bio as author_bio, A.favourite_section as author_favourite_section, P.id as post_id, P.blog_id as post_blog_id, P.author_id as post_author_id, P.created_on as post_created_on, P.section as post_section, P.subject as post_subject, P.draft as draft, P.body as post_body, C.id as comment_id, C.post_id as comment_post_id, C.name as comment_name, C.comment as comment_text, T.id as tag_id, T.name as tag_name from Blog B left outer join Author A on B.author_id = A.id left outer join Post P on B.id = P.blog_id left outer join Comment C on P.id = C.post_id left outer join Post_Tag PT on PT.post_id = P.id left outer join Tag T on PT.tag_id = T.id where B.id = #{id}</select>
你可能想把它映射到一个智能的对象模型,包含一个作者写的博客,有很多的博文,每篇博文有零条或多条的评论和标签。下面是一个完整的复杂结果映射例子(假设作者,博客,博文,评论和标签都是类型的别名) 我们来看看,。但是不用紧张,我们会一步一步来说明。当天最初它看起来令人生畏,但实际上非常简单。
<!-- Very Complex Result Map --><resultMap id="detailedBlogResultMap" type="Blog"> <constructor> <idArg column="blog_id" javaType="int"/> </constructor> <result property="title" column="blog_title"/> <association property="author" javaType="Author"> <id property="id" column="author_id"/> <result property="username" column="author_username"/> <result property="password" column="author_password"/> <result property="email" column="author_email"/> <result property="bio" column="author_bio"/> <result property="favouriteSection" column="author_favourite_section"/> </association> <collection property="posts" ofType="Post"> <id property="id" column="post_id"/> <result property="subject" column="post_subject"/> <association property="author" javaType="Author"/> <collection property="comments" ofType="Comment"> <id property="id" column="comment_id"/> </collection> <collection property="tags" ofType="Tag" > <id property="id" column="tag_id"/> </collection> <discriminator javaType="int" column="draft"> <case value="1" resultType="DraftPost"/> </discriminator> </collection></resultMap>
resultMap 元素有很多子元素和一个值得讨论的结构。下面是 resultMap 元素的概念视图
resultMap
- constructor - 类在实例化时,用来注入结果到构造方法中
- idArg - ID 参数;标记结果作为 ID 可以帮助提高整体效能
- arg - 注入到构造方法的一个普通结果
- id – 一个 ID 结果;标记结果作为 ID 可以帮助提高整体效能
- result – 注入到字段或 JavaBean 属性的普通结果
- association – 一个复杂的类型关联;许多结果将包成这种类型
- 嵌入结果映射 – 结果映射自身的关联,或者参考一个
- collection – 复杂类型的集
- 嵌入结果映射 – 结果映射自身的集,或者参考一个
- discriminator – 使用结果值来决定使用哪个结果映射
- case – 基于某些值的结果映射
- 嵌入结果映射 – 这种情形结果也映射它本身,因此可以包含很多相 同的元素,或者它可以参照一个外部的结果映射。
- case – 基于某些值的结果映射
最佳实践 通常逐步建立结果映射。单元测试的真正帮助在这里。如果你尝试创建一次创建一个向上面示例那样的巨大的结果映射,那么可能会有错误而且很难去控制它来工作。开始简单一些,一步一步的发展。而且要进行单元测试!使用该框架的缺点是它们有时是黑盒(是否可见源代码)。你确定你实现想要的行为的最好选择是编写单元测试。它也可以你帮助得到提交时的错误。
下面一部分将详细说明每个元素。
id & result
<id property="id" column="post_id"/><result property="subject" column="post_subject"/>
这些是结果映射最基本内容。id 和 result 都映射一个单独列的值到简单数据类型(字符串,整型,双精度浮点数,日期等)的单独属性或字段。
这两者之间的唯一不同是 id 表示的结果将是当比较对象实例时用到的标识属性。这帮助来改进整体表现,特别是缓存和嵌入结果映射(也就是联合映射)。
每个都有一些属性:
支持的 JDBC 类型
为了未来的参考,MyBatis 通过包含的 jdbcType 枚举型,支持下面的 JDBC 类型。
BITFLOATCHARTIMESTAMPOTHERUNDEFINEDTINYINTREALVARCHARBINARYBLOGNVARCHARSMALLINTDOUBLELONGVARCHARVARBINARYCLOBNCHARINTEGERNUMERICDATELONGVARBINARYBOOLEANNCLOBBIGINTDECIMALTIMENULLCURSORARRAY构造方法
<constructor> <idArg column="id" javaType="int"/> <arg column="username" javaType="String"/></constructor>
对于大多数数据传输对象(Data Transfer Object,DTO)类型,属性可以起作用,而且像你绝大多数的领域模型,指令也许是你想使用一成不变的类的地方。通常包含引用或查询数据的表很少或基本不变的话对一成不变的类来说是合适的。构造方法注入允许你在初始化时为类设置属性的值,而不用暴露出公有方法。MyBatis 也支持私有属性和私有 JavaBeans 属性来达到这个目的,但是一些人更青睐构造方法注入。构造方法元素支持这个。
看看下面这个构造方法:
public class User { //... public User(int id, String username) { //... }//...}
为了向这个构造方法中注入结果,MyBatis 需要通过它的参数的类型来标识构造方法。Java 没有自查(反射)参数名的方法。所以当创建一个构造方法元素时,保证参数是按顺序排列的,而且数据类型也是确定的。
<constructor> <idArg column="id" javaType="int"/> <arg column="username" javaType="String"/></constructor>
剩余的属性和规则和固定的 id 和 result 元素是相同的。
关联
<association property="author" column="blog_author_id" javaType="Author"> <id property="id" column="author_id"/> <result property="username" column="author_username"/></association>
关联元素处理“有一个”类型的关系。比如,在我们的示例中,一个博客有一个用户。关联映射就工作于这种结果之上。你指定了目标属性,来获取值的列,属性的 java 类型(很多情况下 MyBatis 可以自己算出来),如果需要的话还有 jdbc 类型,如果你想覆盖或获取的结果值还需要类型控制器。
关联中不同的是你需要告诉 MyBatis 如何加载关联。MyBatis 在这方面会有两种不同的方式:
- 嵌套查询:通过执行另外一个 SQL 映射语句来返回预期的复杂类型。
- 嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集。首先,然让我们来查看这个元素的属性。所有的你都会看到,它和普通的只由 select 和
resultMap 属性的结果映射不同。
关联的嵌套查询
示例:
<resultMap id="blogResult" type="Blog"> <association property="author" column="blog_author_id" javaType="Author" select="selectAuthor"/></resultMap><select id="selectBlog" parameterType="int" resultMap="blogResult"> SELECT * FROM BLOG WHERE ID = #{id}</select><select id="selectAuthor" parameterType="int" resultType="Author"> SELECT * FROM AUTHOR WHERE ID = #{id}</select>
我们有两个查询语句:一个来加载博客,另外一个来加载作者,而且博客的结果映射描述了“selectAuthor”语句应该被用来加载它的 author 属性。
其他所有的属性将会被自动加载,假设它们的列和属性名相匹配。
这种方式很简单,但是对于大型数据集合和列表将不会表现很好。问题就是我们熟知的“N+1 查询问题”。概括地讲,N+1 查询问题可以是这样引起的:
- 你执行了一个单独的 SQL 语句来获取结果列表(就是“+1”)。
- 对返回的每条记录,你执行了一个查询语句来为每个加载细节(就是“N”)。
这个问题会导致成百上千的 SQL 语句被执行。这通常不是期望的。
MyBatis 能延迟加载这样的查询就是一个好处,因此你可以分散这些语句同时运行的消耗。然而,如果你加载一个列表,之后迅速迭代来访问嵌套的数据,你会调用所有的延迟加载,这样的行为可能是很糟糕的。
所以还有另外一种方法。
关联的嵌套结果
在上面你已经看到了一个非常复杂的嵌套关联的示例。下面这个是一个非常简单的示例来说明它如何工作。代替了执行一个分离的语句,我们联合博客表和作者表在一起,就像:
<select id="selectBlog" parameterType="int" resultMap="blogResult"> select B.id as blog_id, B.title as blog_title, B.author_id as blog_author_id, A.id as author_id, A.username as author_username, A.password as author_password, A.email as author_email, A.bio as author_bio from Blog B left outer join Author A on B.author_id = A.id where B.id = #{id}</select>
注意这个联合查询, 以及采取保护来确保所有结果被唯一而且清晰的名字来重命名。这使得映射非常简单。现在我们可以映射这个结果:
<resultMap id="blogResult" type="Blog"> <id property="id" column="blog_id" /> <result property="title" column="blog_title"/> <association property="author" column="blog_author_id" javaType="Author" resultMap="authorResult"/></resultMap><resultMap id="authorResult" type="Author"> <id property="id" column="author_id"/> <result property="username" column="author_username"/> <result property="password" column="author_password"/> <result property="email" column="author_email"/> <result property="bio" column="author_bio"/></resultMap>
在上面的示例中你可以看到博客的作者关联代表着“authorResult”结果映射来加载作者实例。
非常重要: 在嵌套据诶过映射中 id 元素扮演了非常重要的角色。应应该通常指定一个或多个属性,它们可以用来唯一标识结果。实际上就是如果你离开她了,但是有一个严重的性能问题时 MyBatis 仍然可以工作。选择的属性越少越好,它们可以唯一地标识结果。主键就是一个显而易见的选择(尽管是联合主键)。
现在,上面的示例用了外部的结果映射元素来映射关联。这使得 Author 结果映射可以重用。然而,如果你不需要重用它的话,或者你仅仅引用你所有的结果映射合到一个单独描述的结果映射中。你可以嵌套结果映射。这里给出使用这种方式的相同示例:
<resultMap id="blogResult" type="Blog"> <id property="id" column="blog_id" /> <result property="title" column="blog_title"/> <association property="author" javaType="Author"> <id property="id" column="author_id"/> <result property="username" column="author_username"/> <result property="password" column="author_password"/> <result property="email" column="author_email"/> <result property="bio" column="author_bio"/> </association></resultMap>
What if the blog has a co-author? The select statement would look like:
<select id="selectBlog" parameterType="int" resultMap="blogResult"> select B.id as blog_id, B.title as blog_title, A.id as author_id, A.username as author_username, A.password as author_password, A.email as author_email, A.bio as author_bio, CA.id as co_author_id, CA.username as co_author_username, CA.password as co_author_password, CA.email as co_author_email, CA.bio as co_author_bio from Blog B left outer join Author A on B.author_id = A.id left outer join Author CA on B.co_author_id = CA.id where B.id = #{id}</select>
Recall that the resultMap for Author is defined as follows.
<resultMap id="authorResult" type="Author"> <id property="id" column="author_id"/> <result property="username" column="author_username"/> <result property="password" column="author_password"/> <result property="email" column="author_email"/> <result property="bio" column="author_bio"/></resultMap>
Because the column names in the results differ from the columns defined in the resultMap, you need to specifycolumnPrefix to reuse the resultMap for mapping co-author results.
<resultMap id="blogResult" type="Blog"> <id property="id" column="blog_id" /> <result property="title" column="blog_title"/> <association property="author" resultMap="authorResult" /> <association property="coAuthor" resultMap="authorResult" columnPrefix="co_" /></resultMap>
上面你已经看到了如何处理“有一个”类型关联。但是“有很多个”是怎样的?下面这个部分就是来讨论这个主题的。
集合
<collection property="posts" ofType="domain.blog.Post"> <id property="id" column="post_id"/> <result property="subject" column="post_subject"/> <result property="body" column="post_body"/></collection>
集合元素的作用几乎和关联是相同的。实际上,它们也很相似,文档的异同是多余的。所以我们更多关注于它们的不同。
我们来继续上面的示例,一个博客只有一个作者。但是博客有很多文章。在博客类中,这可以由下面这样的写法来表示:
private List<Post> posts;
要映射嵌套结果集合到 List 中,我们使用集合元素。就像关联元素一样,我们可以从连接中使用嵌套查询,或者嵌套结果。
集合的嵌套查询
首先,让我们看看使用嵌套查询来为博客加载文章。
<resultMap id="blogResult" type="Blog"> <collection property="posts" javaType="ArrayList" column="blog_id" ofType="Post" select="selectPostsForBlog"/></resultMap><select id="selectBlog" parameterType="int" resultMap="blogResult"> SELECT * FROM BLOG WHERE ID = #{id}</select><select id="selectPostsForBlog" parameterType="int" resultType="Blog"> SELECT * FROM POST WHERE BLOG_ID = #{id}</select>
这里你应该注意很多东西,但大部分代码和上面的关联元素是非常相似的。首先,你应该注意我们使用的是集合元素。然后要注意那个新的“ofType”属性。这个属性用来区分JavaBean(或字段)属性类型和集合包含的类型来说是很重要的。所以你可以读出下面这个映射:
<collection property="posts" javaType="ArrayList" column="blog_id" ofType="Post" select="selectPostsForBlog"/>
读作: “在 Post 类型的 ArrayList 中的 posts 的集合。”
javaType 属性是不需要的,因为 MyBatis 在很多情况下会为你算出来。所以你可以缩短写法:
<collection property="posts" column="blog_id" ofType="Post" select="selectPostsForBlog"/>
集合的嵌套结果
至此,你可以猜测集合的嵌套结果是如何来工作的,因为它和关联完全相同,除了它应用了一个“ofType”属性
First, let's look at the SQL:
<select id="selectBlog" parameterType="int" resultMap="blogResult"> select B.id as blog_id, B.title as blog_title, B.author_id as blog_author_id, P.id as post_id, P.subject as post_subject, P.body as post_body, from Blog B left outer join Post P on B.id = P.blog_id where B.id = #{id}</select>
我们又一次联合了博客表和文章表,而且关注于保证特性,结果列标签的简单映射。现在用文章映射集合映射博客,可以简单写为:
<resultMap id="blogResult" type="Blog"> <id property="id" column="blog_id" /> <result property="title" column="blog_title"/> <collection property="posts" ofType="Post"> <id property="id" column="post_id"/> <result property="subject" column="post_subject"/> <result property="body" column="post_body"/> </collection></resultMap>
同样,要记得 id 元素的重要性,如果你不记得了,请阅读上面的关联部分。
同样,如果你引用更长的形式允许你的结果映射的更多重用,你可以使用下面这个替代的映射:
<resultMap id="blogResult" type="Blog"> <id property="id" column="blog_id" /> <result property="title" column="blog_title"/> <collection property="posts" ofType="Post" resultMap="blogPostResult" columnPrefix="post_"/></resultMap><resultMap id="blogPostResult" type="Post"> <id property="id" column="id"/> <result property="subject" column="subject"/> <result property="body" column="body"/></resultMap>
注意 这个对你所映射的内容没有深度,广度或关联和集合相联合的限制。当映射它们时你应该在大脑中保留它们的表现。你的应用在找到最佳方法前要一直进行的单元测试和性能测试。好在 myBatis 让你后来可以改变想法,而不对你的代码造成很小(或任何)影响。
高级关联和集合映射是一个深度的主题。文档只能给你介绍到这了。加上一点联系,你会很快清楚它们的用法。
鉴别器
<discriminator javaType="int" column="draft"> <case value="1" resultType="DraftPost"/></discriminator>
有时一个单独的数据库查询也许返回很多不同(但是希望有些关联)数据类型的结果集。鉴别器元素就是被设计来处理这个情况的,还有包括类的继承层次结构。鉴别器非常容易理解,因为它的表现很像 Java 语言中的 switch 语句。
定义鉴别器指定了 column 和 javaType 属性。列是 MyBatis 查找比较值的地方。JavaType是需要被用来保证等价测试的合适类型(尽管字符串在很多情形下都会有用)。比如:
<resultMap id="vehicleResult" type="Vehicle"> <id property="id" column="id" /> <result property="vin" column="vin"/> <result property="year" column="year"/> <result property="make" column="make"/> <result property="model" column="model"/> <result property="color" column="color"/> <discriminator javaType="int" column="vehicle_type"> <case value="1" resultMap="carResult"/> <case value="2" resultMap="truckResult"/> <case value="3" resultMap="vanResult"/> <case value="4" resultMap="suvResult"/> </discriminator></resultMap>
在这个示例中,MyBatis 会从结果集中得到每条记录,然后比较它的 vehicle 类型的值。如果它匹配任何一个鉴别器的实例,那么就使用这个实例指定的结果映射。换句话说,这样做完全是剩余的结果映射被忽略(除非它被扩展,这在第二个示例中讨论)。如果没有任何一个实例相匹配,那么 MyBatis 仅仅使用鉴别器块外定义的结果映射。所以,如果 carResult按如下声明:
<resultMap id="carResult" type="Car"> <result property="doorCount" column="door_count" /></resultMap>
那么只有 doorCount 属性会被加载。这步完成后完整地允许鉴别器实例的独立组,尽管和父结果映射可能没有什么关系。这种情况下,我们当然知道 cars 和 vehicles 之间有关系,如 Car 是一个 Vehicle 实例。因此,我们想要剩余的属性也被加载。我们设置的结果映射的简单改变如下。
<resultMap id="carResult" type="Car" extends="vehicleResult"> <result property="doorCount" column="door_count" /></resultMap>
现在 vehicleResult 和 carResult 的属性都会被加载了。
尽管曾经有些人会发现这个外部映射定义会多少有一些令人厌烦之处。因此还有另外一种语法来做简洁的映射风格。比如:
<resultMap id="vehicleResult" type="Vehicle"> <id property="id" column="id" /> <result property="vin" column="vin"/> <result property="year" column="year"/> <result property="make" column="make"/> <result property="model" column="model"/> <result property="color" column="color"/> <discriminator javaType="int" column="vehicle_type"> <case value="1" resultType="carResult"> <result property="doorCount" column="door_count" /> </case> <case value="2" resultType="truckResult"> <result property="boxSize" column="box_size" /> <result property="extendedCab" column="extended_cab" /> </case> <case value="3" resultType="vanResult"> <result property="powerSlidingDoor" column="power_sliding_door" /> </case> <case value="4" resultType="suvResult"> <result property="allWheelDrive" column="all_wheel_drive" /> </case> </discriminator></resultMap>
要记得 这些都是结果映射,如果你不指定任何结果,那么 MyBatis 将会为你自动匹配列和属性。所以这些例子中的大部分是很冗长的,而其实是不需要的。也就是说,很多数据库是很复杂的,我们不太可能对所有示例都能依靠它。
Auto-mapping
As you have already seen in the previous sections, in simple cases MyBatis can auto-map the results for you and in others you will need to build a result map. But as you will see in this section you can also mix both strategies. Let's have a deeper look at how auto-mapping works.
When auto-mapping results MyBatis will get the column name and look for a property with the same name ignoring case. That means that if a column namedID and property namedid are found, MyBatis will set the id property with theID column value.
Usually database columns are named using uppercase letters and underscores between words and java properties often follow the camelcase naming covention. To enable the auto-mapping between them set the settingmapUnderscoreToCamelCase to true.
Auto-mapping works even when there is an specific result map. When this happens, for each result map, all columns that are present in the ResultSet that have not a manual mapping will be auto-mapped, then manual mappings will be processed. In the following sample id and userName columns will be auto-mapped and hashed_password column will be mapped.
<select id="selectUsers" parameterType="int" resultType="User"> select user_id as "id", user_name as "userName", hashed_password from some_table where id = #{id}</select>
<resultMap id="userResultMap" type="User"> <result property="password" column="hashed_password"/></resultMap>
There are three auto-mapping levels:
- NONE - disables auto-mapping. Only manually mapped properties will be set.
- PARTIAL - will auto-map results except those that have nested result mappings defined inside (joins).
- FULL - auto-maps everything.
The default value is PARTIAL, and it is so for a reason. When FULL is used auto-mapping will be performed when processing join results and joins retrieve data of several different entities in the same row hence this may result in undesired mappings. To understand the risk have a look at the following sample:
<select id="selectBlog" parameterType="int" resultMap="blogResult"> select B.id, B.title, A.username, from Blog B left outer join Author A on B.author_id = A.id where B.id = #{id}</select>
<resultMap id="blogResult" type="Blog"> <association property="author" javaType="Author" resultMap="authorResult"/></resultMap><resultMap id="authorResult" type="Author"> <result property="username" column="author_username"/></resultMap>
With this result map both Blog and Author will be auto-mapped. But note thatAuthor has anid property and there is a column named id in the ResultSet so Author's id will be filled with Blog's id, and that is not what you were expecting. So use theFULL option with caution.
缓存
MyBatis 包含一个非常强大的查询缓存特性,它可以非常方便地配置和定制。MyBatis 3中的缓存实现的很多改进都已经实现了,使得它更加强大而且易于配置。
默认情况下是没有开启缓存的,除了局部的 session 缓存,可以增强变现而且处理循环依赖也是必须的。要开启二级缓存,你需要在你的 SQL 映射文件中添加一行:
<cache/>
字面上看就是这样。这个简单语句的效果如下:
- 映射语句文件中的所有 select 语句将会被缓存。
- 映射语句文件中的所有 insert,update 和 delete 语句会刷新缓存。
- 缓存会使用 Least Recently Used(LRU,最近最少使用的)算法来收回。
- 根据时间表(比如 no Flush Interval,没有刷新间隔), 缓存不会以任何时间顺序 来刷新。
- 缓存会存储列表集合或对象(无论查询方法返回什么)的 1024 个引用。
- 缓存会被视为是 read/write(可读/可写)的缓存,意味着对象检索不是共享的,而且可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
所有的这些属性都可以通过缓存元素的属性来修改。比如:
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
这个更高级的配置创建了一个 FIFO 缓存,并每隔 60 秒刷新,存数结果对象或列表的512 个引用,而且返回的对象被认为是只读的,因此在不同线程中的调用者之间修改它们会导致冲突。
可用的收回策略有:
- LRU – 最近最少使用的:移除最长时间不被使用的对象。
- FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
- SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
- WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
默认的是 LRU。
flushInterval(刷新间隔)可以被设置为任意的正整数,而且它们代表一个合理的毫秒形式的时间段。默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新。
size(引用数目)可以被设置为任意正整数,要记住你缓存的对象数目和你运行环境的可用内存资源数目。默认值是 1024。
readOnly(只读)属性可以被设置为 true 或 false。只读的缓存会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。可读写的缓存会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是 false。
使用自定义缓存
除了这些自定义缓存的方式,你也可以通过实现你自己的缓存或为其他第三方缓存方案创建适配器来完全覆盖缓存行为。
<cache type="com.domain.something.MyCustomCache"/>
这个示 例展 示了 如何 使用 一个 自定义 的缓 存实 现。type 属 性指 定的 类必 须实现org.mybatis.cache.Cache 接口。这个接口是 MyBatis 框架中很多复杂的接口之一,但是简单给定它做什么就行。
public interface Cache { String getId(); int getSize(); void putObject(Object key, Object value); Object getObject(Object key); boolean hasKey(Object key); Object removeObject(Object key); void clear(); ReadWriteLock getReadWriteLock();}
要配置你的缓存,简单和公有的 JavaBeans 属性来配置你的缓存实现,而且是通过 cache元素来传递属性,比如,下面代码会在你的缓存实现中调用一个称为“setCacheFile(String file)”的方法:
<cache type="com.domain.something.MyCustomCache"> <property name="cacheFile" value="/tmp/my-custom-cache.tmp"/></cache>
你可以使用所有简单类型作为 JavaBeans 的属性,MyBatis 会进行转换。
记得缓存配置和缓存实例是绑定在 SQL 映射文件的命名空间是很重要的。因此,所有在相同命名空间的语句正如绑定的缓存一样。语句可以修改和缓存交互的方式,或在语句的语句的基础上使用两种简单的属性来完全排除它们。默认情况下,语句可以这样来配置:
<select ... flushCache="false" useCache="true"/><insert ... flushCache="true"/><update ... flushCache="true"/><delete ... flushCache="true"/>
因为那些是默认的,你明显不能明确地以这种方式来配置一条语句。相反,如果你想改变默认的行为,只能设置 flushCache 和 useCache 属性。比如,在一些情况下你也许想排除从缓存中查询特定语句结果,或者你也许想要一个查询语句来刷新缓存。相似地,你也许有一些更新语句依靠执行而不需要刷新缓存。
参照缓存
回想一下上一节内容,这个特殊命名空间的唯一缓存会被使用或者刷新相同命名空间内的语句。也许将来的某个时候,你会想在命名空间中共享相同的缓存配置和实例。在这样的情况下你可以使用 cache-ref 元素来引用另外一个缓存。
<cache-ref namespace="com.someone.application.data.SomeMapper"/>
- MyBatis
- MyBatis
- Mybatis
- myBatis
- mybatis
- MyBatis
- mybatis
- Mybatis
- MyBatis
- Mybatis
- mybatis
- MyBatis
- MyBatis
- mybatis
- MyBatis
- mybatis
- mybatis
- mybatis
- 关于用QT的QML开发Android程序的点滴记录
- Win7下VS2010使用STLPort .
- SQL 数据表的创建 删除 添加字段 删除整表
- db_name,instance_name,service_names,db_domain,dbid,oracle_sid等区别与联系
- 改变能改变的,接受不能改变的
- MyBatis
- sql锁进程相关操作
- junit4光速入门
- 人家人爱A^B
- 【XXXXX】近几个月来完成的工作提纲
- centos上支持打开chm文件
- 二分搜索
- N!的最高位
- 網頁模板