MyBatis 3 User Guide Simplified Chinese
- 格式:pdf
- 大小:1.08 MB
- 文档页数:56
MyBatis3教程
MyBatis3教程:
(官⽅标准配置⽂档)
(MyBatis与Spring集成的官⽅标准配置⽂档)
(MyBatis代码⽣成器官⽅标准配置⽂档)
MyBatis简介:
MyBatis是iBatis的前⾝,所⽰在包名上还是沿⽤以前的iBatis。
MyBatis是⽀持普通SQL查询,存储过程和⾼级映射的优秀持久层框架。
MyBatis消除了⼏乎所有的JDBC代码和参数的⼿⼯设置以及结果集的检索。
MyBatis使⽤简单的XML或注解⽤于配置和原始映射,将接⼝和Java的POJOs(Plan Old Java Objects,普通的Java对象)映射成数据库中的记录。
ORM⼯具的基本思想:
⽆论是⽤过的Hibernate,MyBatis,他们都有⼀个共同点:
1、从配置⽂件(通常是XML配置⽂件中)得到SessionFactory。
2、由SessionFactory产⽣Session。
3、在Session中完成对数据的增删改查和事务提交等。
4、在⽤完之后关闭Session。
5、在Java对象和数据库之间有做Mapping的配置⽂件,也通常是XML⽂件。
项⽬源码:
总结:
1、我的实践笔记:,每篇实践笔记都⾃带测试⼯程例⼦。
2、这个教程在阅读时不要挑章节,最好是从第⼀章开始连贯的阅读,因为有些章节省略了部分源码的讲解,只保留了核⼼部分,只有从第⼀章开始才会知道⼤概有哪些⽂件需要配置。
MyBatisPlus3.x中使⽤代码⽣成器(全注释)场景MyBaitsPlus3.x与2.x是不⼀样的。
这⾥使⽤3.0.1版本。
官⽅⽂档这⾥在IDEA上的SpringBoot项⽬中进⾏代码⽣成测试。
实现添加依赖添加代码⽣成器依赖<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.2.0</version></dependency>注意:MyBatis-Plus 从 3.0.3 之后移除了代码⽣成器与模板引擎的默认依赖,需要⼿动添加相关依赖<!-- 模板引擎velocity start--><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.0</version></dependency><!-- 模板引擎velocity end--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.0.1</version></dependency>模板引擎MyBatis-Plus ⽀持 Velocity(默认)、Freemarker、Beetl,⽤户可以选择⾃⼰熟悉的模板引擎。
整合Spring3及MyBatis3对于整合Spring及Mybatis不作详细介绍,可以参考:MyBatis 3 User Guide Simplified Chinese.pdf,贴出我的主要代码如下:UserMapper Interface:Java代码package org.denger.mapper;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Select;import er;public interface UserMapper {@Select("select * from tab_uc_account where id=#{userId}")User getUser(@Param("userId") Long userId);}application-context.xml:Xml代码<?xml version="1.0"encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:context="http://www.sprin /schema/context"xmlns:aop="/schema/aop"xmlns:tx="http://www.springfram /schema/tx"xsi:schemaLocation="/schema/beans http://www.springfram /schema/beans/spring-beans-3.0.xsd /schema/conte xt /schema/context/spring-context-3.0.xsd http://www.springfr /schema/aop /schema/aop/spring-aop-2.0.xsd htt p:///schema/tx /schema/tx/spring-tx -2.0.xsd"><!-- Provided by annotation-based configuration --><context:annotation-config/><!--JDBC Transaction Manage --><bean id="dataSourceProxy"class="org.springframework.jdbc.datasource.TransactionAwareDa taSourceProxy"><constructor-arg><ref bean="dataSource"/></constructor-arg></bean><!-- The JDBC c3p0 dataSource bean--><bean id="dataSource"class="boPooledDataSource"destroy-meth od="close"><property name="driverClass"value="com.mysql.jdbc.Driver"/><property name="jdbcUrl"value="jdbc:mysql://127.0.0.1:3306/noah"/><property name="user"value="root"/><property name="password"value="123456"/></bean><!--MyBatis integration with Spring as define sqlSessionFactory --><bean id="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource"ref="dataSource"/></bean><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="sqlSessionFactory"ref="sqlSessionFactory"/><property name="basePackage"value="org.denger.mapper"></property></bean></beans>test Class:Java代码package org.denger.mapper;import org.junit.Assert;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;@ContextConfiguration(locations = { "/application-context.xml"})public class UserMapperTest extends AbstractJUnit4SpringContextTests{@Autowiredpublic UserMapper userMapper;@Testpublic void testGetUser(){Assert.assertNotNull(userMapper.getUser(300L));}}实现原理分析对于以上极其简单代码看上去并无特殊之处,主要亮点在于UserMapper居然不用实现类,而且在调用getUser的时候,也是使用直接调用了UserMapper实现类,那么Mybatis是如何去实现UserMapper的接口的呢?可能你马上能想到的实现机制就是通过动态代理方式,好吧,看看MyBatis整个的代理过程吧。
Mybatis3详解(四)----SQL映射⽂件详解(XxxMapper.xml)1映射器是Mybatis中最复杂并且是最重要的组件。
它由⼀个接⼝和xml映射⽂件(或者注解)组成。
在映射器中我们可以配置各类SQL、动态SQL、缓存、存储过程、级联等复杂的内容。
并且通过简易的映射规则映射到指定的POJO或者其它对象上,映射器能有效的消除JDBC的底层代码。
在Mybatis的应⽤程序开发中,映射器的开发⼯作量占全部⼯作量的80%,可见其重要性。
映射⽂件的作⽤是⽤来配置SQL映射语句,根据不同的SQL语句性质,使⽤不同的标签,其中常⽤的标签有:<select>、<insert>、<update>、<delete>。
下⾯列出了SQL 映射⽂件的⼏个顶级元素(按照应被定义的顺序列出):元素描述cache该命名空间的缓存配置(会在缓存部分进⾏讲解)cache-ref引⽤其它命名空间的缓存配置resultMap描述如何从数据库结果集中加载对象,它是最复杂也是最强⼤的元素parameterMap定义参数映射。
此元素已被废弃,并可能在将来被移除!请使⽤⾏内参数映射parameType。
所以本⽂中不会介绍此元素sql可被其它语句引⽤的可重⽤语句块select映射查询语句insert映射插⼊语句update映射更新语句delete映射删除语句2select元素表⽰SQL 的select 语句,⽤于查询,⽽查询语句是我们⽇常中⽤的最多的,使⽤的多就意味它有着强⼤和复杂的功能,所以我们先来看看select元素的属性有哪些(加粗为最常⽤的)。
select元素中的属性属性描述id在命名空间中唯⼀的标识符,可以被⽤来引⽤这条语句parameterType将会传⼊这条语句的参数类的完全限定名或别名。
这个属性是可选的,因为 MyBatis 可以通过类型处理器(TypeHandler)推断出具体传⼊语句的参数,默认值为未设置(unset)parameterMap这是引⽤外部 parameterMap 的已经被废弃的⽅法。
MyBatis Spring1.0.0-RC3参考文档MyBatis 社区()Copyright © 2010本文档的拷贝仅允许您个人使用或分发给其他用户,但是不能收取任何费用,后期的发布无论是印刷版或电子版,也会进行版权声明。
本文档由南磊(nanlei1987@)翻译目录第一章介绍 (3)1.1 整合动机 (3)1.2 要求 (3)1.3 感谢 (3)第二章入门 (4)2.1 安装 (4)2.2 快速创建 (4)第三章SqlSessionFactoryBean (6)3.1 创建 (6)3.2 属性 (6)第四章事务 (8)4.1 标准配置 (8)4.2 容器管理事务 (8)第五章使用SqlSession (9)5.1 SqlSessionSupport (9)5.2 SqlSessionTemplate (9)第六章MapperFactoryBean (11)6.1 创建 (11)6.2 注入映射器 (11)6.3 自动配置 (12)第七章使用MyBatis API (13)第八章示例代码 (14)第一章介绍1.1 整合动机正如第二版,Spring仅支持iBatis2。
那么我们就想将MyBatis3的支持加入到Spring3.0(参考Spring的Jira的问题)中。
不幸的是,Spring 3.0的开发在MyBatis 3.0官方发布前就结束了。
因为Spring开发团队不想发布一个基于非发行版的MyBatis的整合支持,那么Spring 官方的支持就不得不等到至少3.1版本了。
要在Spring中支持MyBatis,MyBatis社区认为现在应该是自己团结贡献者和有兴趣的人一起来开始进行Spring和MyBatis整合的时候了。
这个小类库就来创建丢失的粘贴Spring和MyBtatis这两个流行框架的胶水。
减少用户不得不来配置MyBatis和Spring 3.X上下文环境的样板和冗余代码。
Mybatis的配置⽂件和映射⽂件详解⼀、Mybatis的全局配置⽂件1、SqlMapConfig.xml(名称可变)是mybatis的全局配置⽂件,配置内容如下:properties(属性)settings(全局配置参数)typeAliases(类型别名)typeHandlers(类型处理器)objectFactory(对象⼯⼚)plugins(插件)environments(环境集合属性对象)environment(环境⼦属性对象)transactionManager(事务管理)dataSource(数据源)mappers(映射器)2、properties将数据库连接参数单独配置在db.properties(名称可变)中,放在类路径下。
这样只需要在SqlMapConfig.xml中加载db.properties的属性值。
这样在SqlMapConfig.xml中就不需要对数据库连接参数硬编码。
将数据库连接参数只配置在db.properties中,原因:⽅便对参数进⾏统⼀管理,其它xml可以引⽤该db.properties例如:db.propertiesjdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatisername=rootjdbc.password=root相应的SqlMapConfig.xml<properties resource="db.properties"/><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${ername}"/><property name="password" value="${jdbc.password}"/></dataSource></environment></environments>注意: MyBatis 将按照下⾯的顺序来加载属性:⾸先、在properties标签中指定的属性⽂件⾸先被读取。
Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(一)2012-07-31 15:35 198人阅读评论(0) 收藏举报Spring更新到3.0之后,其MVC框架加入了一个非常不错的东西——那就是REST。
它的开放式特性,与Spring的无缝集成,以及Spring框架的优秀表现,使得现在很多公司将其作为新的系统开发框架。
大象根据实际的项目经验,以之前SSH2例子为基础,对其进行一次大改造,详细的为大家讲解如何实现SSM3全注解式的开发。
这次大象将采取两种构建方式,一是很多人喜欢用的MyEclipse,另一个,则是用Eclipse+Maven。
这一篇,将主要讲解开发环境设置与Maven构建方式。
1、开发环境JDK1.6.0_18Eclipse3.2.1 MyEclipse5.1.0Eclipse-JEE-HELIOS-SR2 Maven3.0.1 m2eclipse0.12.1.20110112-1712Tomcat6.0.10 maven-jetty-plugin6.1.26MySQL5.0.27 Navicat Lite for MySQL 8.1.20每个人的开发环境可能会有差异,但有一点我需要说明的是,JDK的版本不得低于1.5,因为用到了很多1.5版才支持的新特性。
Tomcat、Jetty、Maven和MySQL请不要低于我所用的版本,因为我没在其它的版本上进行测试。
Navicat则是MySQL数据库的图形化操作工具。
接下来我将介绍如何在Eclipse3.6中,使用m2eclipse插件构建web应用及测试开发环境。
2、设置MavenMaven的安装很简单,只需要解压即可,请设置PATH变量,这样可以使用命令行进行操作,然后就要在%MAVEN_HOME%\conf目录下,对settings.xml作下修改这就是设置本地仓库,目录可以根据自己的实际情况更改,不过请使用"/"正斜杠,因为我在实际使用中,发现反斜杠有时候获取不到资源。
MyBatis 3 – S chema M igration S ystemUser GuideNOTE: T his g uide i s n ot a bout m igrating f rom o lder v ersions o f M yBatis. I t i s a m anual a bout a tool t hat w ill c hange t he w ay y ou m anage c hanges t o y our d atabase.MyBatis 3 M igrations IntroductionEvolving d atabases h as b een o ne o f t he m ajor c hallenges f or s oftware d evelopment. O ften t imes, regardless o f o ur s oftware d evelopment m ethodology, t he d atabase f ollows a d ifferent c hange management p rocess. D espite o ur b est e fforts, f ew t ools a nd p ractices h ave b een a ble t o c hange t hat. The t ools o f t he p ast h ave b een G UI c entric, p roprietary f or a p articular d atabase a nd/or c arried a s teep license c ost. Y et, a t t he e nd o f t he d ay t hey s uffered f rom t he s ame c hallenges.Recently, a f ew t ools a rrived a nd c hanged a ll o f t hat. T hey d id s o b y e mbracing s implicity a nd a f ew simple r ules f or d atabase e volution t o f ollow. A c ouple o f g ood e xamples a re R ails M igrations a nd dbdeploy. B oth t ools a re s imilar i n p urpose, b ut q uite d ifferent i n i mplementation. T he M yBatis Schema M igration S ystem d raws f rom b oth a nd s eeks t o b e t he b est m igration t ool o f i ts k ind.GoalsTo a chieve a g ood d atabase c hange m anagement p ractice, w e n eed t o i dentify a f ew k ey g oals. Thus, t he M yBatis S chema M igration S ystem (or M yBatis M igrations f or s hort) s eeks t o: •Work w ith a ny d atabase, n ew o r e xisting•Leverage t he s ource c ontrol s ystem (e.g. S ubversion)•Enable c oncurrent d evelopers o r t eams t o w ork i ndependently•Allow c onflicts v ery v isible a nd e asily m anageable•Allow f or f orward a nd b ackward m igration (evolve, d evolve r espectively)•Make t he c urrent s tatus o f t he d atabase e asily a ccessible a nd c omprehensible•Enable m igrations d espite a ccess p rivileges o r b ureaucracy•Work w ith a ny m ethodology•Encourages g ood, c onsistent p racticesInstallationInstallation i s s imply a m atter o f u nzipping t he p ackage t o a d irectory o f y our c hoosing. T here a re generally t wo w ays t o w ork w ith t his t ool:•Unzip i t t o a c entral l ocation. A dd M IGRATIONS_HOME t o y our e nvironment v ariables, a nd a dd MIGRATIONS_HOME t o y our p ath. T his i s a c ommon o ption, p opular a mong s imilar t ools l ikeAnt o r M aven.•Unzip i t i nto a d irectory i n y our w orkspace f or a p roject t hat y ou’re c urrently w orking o n, t hus keeping a ll o f t he d ependencies a nd t he t ool v ersion i solated w ithin t he p roject. I t’s a s mallframework, a nd t his o ption h as t he a dvantage o f p ortability a nd z ero s etup f or d evelopers n ew to t he p roject.What’s I ncluded?The M yBatis M igrations p ackage i s s mall a nd s imple. T he f ollowing i s t he c ontents o f t he u nzipped package:./lib/mybatis-3-core-3.0.0.188.jar./migrate.migrate.cmdThe s ingle M yBatis J AR f ile i s t he o nly d ependency t hat M yBatis M igrations h as. T he t wo s cript f iles d o the s ame t hing, b ut a s y ou c an s ee, o ne i s f or *nix s hells a nd t he o ther i s f or W indows (Note: c ygwin users s hould s till c all t he .cmd v ersion).The ‘migrate’ C ommandThe e ntire M igrations s ystem c an b e a ccessed t hrough t his o ne s imple c ommand. Y ou c an a ccess t he built-‐in h elp b y t yping: m igrate --helpCalling t he m igrate c ommand w ith n o o ptions o r i nvalid o ptions a lso p roduces t he h elp m essage. H ere’s the o utput o f t he h elp c ommand:Usage: migrate command [parameter] [--path=<directory>] [--env=<environment>][--template=<path to template>]--path=<directory> Path to repository. Default current working directory.--env=<environment> Environment to configure. Default environment is 'development'.--force Forces script to continue even if SQL errors are encountered.--help Displays this usage message.--trace Shows additional error details (if any).--template (Optional) Specify template to be used with ‘new’commandCommands:init Creates (if necessary) and initializes a migration path.bootstrap Runs the bootstrap SQL script (see scripts/bootstrap.sql for more).new <description> Creates a new migration with the provided description.up Run all unapplied migrations.down Undoes the last migration applied to the database.version <version> Migrates the database up or down to the specified version.pending Force executes pending migrations out of order (not recommended).status Prints the changelog from the database if the changelog table exists.script <v1> <v2> Generates a delta migration script from version v1 to v2 (undo if v1 > v2). We’ll g o t hrough e ach o f t hese c ommands i n d etail, b ut f irst, l et’s t alk a bout l ifecycle.The M yBatis M igrations L ifecycleDatabase c hange m anagement i s d ifficult a t t he b est o f t imes, s o t o m ake t he s ituation b etter, i t’s important t o h ave a g ood d atabase e volution s trategy. T hat e mployed b y M yBatis M igrations t argets a few k ey g oals:•Consistent – T he s chema s hould b e p redictable o n e very m achine i t’s c reated o n.•Repeatable – T he s chema c an b e d estroyed a nd r ecreated a p redictable w ay.•Reversible – C hanges s hould b e a ble t o b e r olled b ack, o r u ndone.•Versioned – T he v ersion o f t he s chema s hould b e i dentifiable (via q uery o r t ool).•Auditable – T he s chema e volution s hould b e a uditable a nd t he c hanges t o i t l ogged.•Automated – T he e volution (or d evolution) o f t he s chema s hould b e f ully a utomated.•Serial – T he e volution i n t he d atabase s hould n ever b ranch o r e volve c onditionally.•Immutable C hanges – N o p ast a pplied a lter o r e volution o f t he d atabase s hould b e m odified, instead a n ew c hange s hould b e c reated.•Concurrently M odifiable – T he s chema s hould b e s afely m odifiable b y m ultiple p eople o r t eams in a w ay t hat e ncourages t eamwork, c ommunication a nd e asy i dentification o f c onflicts, w ithout depending o n t ext c omparisons (diff) o r a ny p articular s ource c ontrol f eature (conflicts), b utshould w ork v ery w ell w ith s ource c ontrol s ystems.T hus, t he l ifecycle o f a s chema m anaged w ith M yBatis M igrations i s a s f ollows:1.Initialize R epository2.Bootstrap d atabase s chema3.Create a n ew m igration (or m any m igrations)4.Apply m igrationsOptional s teps i nclude:•Revert m igrations i f n ecessary t o r esolve c onflicts•Apply p ending m igrations o ut o f o rder i f i t’s s afe t o d o s o•Generate m igration s cripts t o b e r un “offline” i n e nvironments t hat a re b eyond y our c ontrol •Get t he s tatus o f t he s ystem a t a ny t imeThe f ollowing c ommand d iscussions w ill p rovide m ore d etail a bout h ow t his l ifecycle w orks.initThe i nit c ommand i nitializes a n ew ‘migration p ath’, a lso c alled a ‘repository’ (of m igration s cripts). Regardless o f w hether y our w orking w ith a n ew d atabase o r a n e xisting o ne, y ou’ll r un i nit t o c reate t he workspace i n w hich y ou’ll p lace e verything y ou n eed t o m anage d atabase c hange. R unning t his command w ill c reate t he d irectory s pecified b y t he -‐-‐path o ption (which i s t he c urrent w orking d irectory by d efault).Here’s a n e xample o f r unning t he i nit c ommand:/$ migrate --path=/home/cbegin/testdb initIf I w as a lready i n t he /home/cbegin/testdb d irectory, I c ould s imply r un:/home/cbegin/testdb$ migrate initWhen t he c ommand i s c ompleted, t he d irectory w ill c ontain t he f ollowing s ub-‐directories:./driversPlace y our J DBC d river .jar o r .zip f iles i n t his d irectory. U pon r unning a m igration, t he d rivers w ill b e dynamically l oaded../environmentsIn t he e nvironments f older y ou w ill f ind .properties f iles t hat r epresent y our d atabase i nstances. B y default a d evelopment.properties f ile i s c reated f or y ou t o c onfigure y our d evelopment t ime d atabase properties. Y ou c an a lso c reate t est.properties a nd p roduction.properties f iles. D etails a bout t he properties t hemselves f ollow l ater i n t his d ocument. T he e nvironment c an b e s pecified w hen r unning a migration b y u sing t he -‐-‐env=<environment> o ption (without t he p ath o r ".properties" p art).The d efault e nvironment i s "development". T he p roperties f ile i s s elf d ocumented, b ut h ere i t i s f or reference:## Base time zone to ensure times are consistent across machines time_zone=GMT+0:00## The character set that scripts are encoded with# script_char_set=UTF-8## JDBC connection properties.driver=url=username=password=# Name of the table that tracks changes to the databasechangelog=CHANGELOG# If set to true, each statement is isolated# in its own transaction. Otherwise the entire# script is executed in one transaction.auto_commit=false# This controls how statements are delimited.# By default statements are delimited by an# end of line semicolon. Some databases may# (e.g. MS SQL Server) may require a full line# delimiter such as GO.delimiter=;full_line_delimiter=false# This ignores the line delimiters and# simply sends the entire script at once.# Use with JDBC drivers that can accept large# blocks of delimited text at once.send_full_script=false# Custom driver path to avoid copying your drivers# driver_path=./scriptsThis d irectory c ontains y our m igration S QL f iles. T hese a re t he f iles t hat c ontain y our D DL t o b oth upgrade a nd d owngrade y our d atabase s tructure. B y d efault, t he d irectory w ill c ontain t he s cript t o create t he c hangelog t able, p lus o ne e mpty e xample m igration s cript. T o c reate a n ew m igration s cript, use t he "new" c ommand. T o r un a ll p ending m igrations, u se t he "up" c ommand. T o u ndo t he l ast migration a pplied, u se t he "down" c ommand e tc.bootstrapIf y ou’re w orking f rom a n e xisting d atabase, y ou n eed t o s tart f rom a k nown s tate. T here’s n o p oint i n trying t o r ewind t ime a nd s hoehorn y our e xisting d atabase i nto a s eries o f m igration s cripts. I t’s m ore practical t o j ust a ccept t he c urrent s tate o f y our d atabase s chema a nd i dentify t his a s t he s tarting p oint. The b ootstrap s cript a nd c ommand e xist f or t his r eason. I n t he s cripts d irectory y ou’ll f ind bootstrap.sql. Y ou c an p ut y our e xisting D DL s cript i n t his f ile. I f y ou d on’t h ave a D DL s cript, y ou c an export y our e xisting d atabase s chema a nd p ut i t i n t he b ootstrap f ile. Y ou’ll w ant t o c lean i t u p s o t hat i t doesn’t c ontain a nything s pecific t o a ny o ne e nvironment, b ut o therwise a lmost a ny s cript s hould w ork. Watch o ut f or D DL t hat c ontains c onditional e lements o r b ranching l ogic t hat c ould g enerate m ultiple schemas. W hile t his i s s ometimes n ecessary, i t’s a r eally g ood i dea t o t ry t o e liminate t his a spect o f y our database s chema (put s uch c onditional a nd b ranching l ogic i n y our c ode o r s tored p rocedures i nstead). If y ou h ave m ultiple D DL f iles, y ou’ll h ave t o m erge t hem i nto t he s ingle b ootstrap f ile. B ut w orry n ot, it’s t he l ast t ime y ou’ll e ver m odify i t. O ne o f t he r ules a bove w as i mmutable c hange s cripts… t he bootstrap i s i ncluded i n t hat r ule.N ote: T he b ootstrap.sql i s a p lain t ext f ile a nd i s n ot a v alid “migration” t hat y ou’ll l earn a bout l ater. It’s m eant t o b e s imilar t o t he s cripts y ou p robably a lready u se. T herefore y ou c annot r ollback t he bootstrap f ile, n or i s i t t racked i n t he a udit l ogs… w ithout e xception, w hatever y ou p ut i n t he b ootstrap file c annot l everage t he b enefits o f t he o ther m igration c ommands. B ut w e h ave t o s tart s omewhere, and i t’s b est t o l ook f orward.To r un t he b ootstrap f ile, y ou s imply c all t he b ootstrap c ommand. Y ou d o t his o nce t o i nitialize y our database i nto a k nown w orking s tate. F rom t hen o n, y ou’ll u se m igration s cripts t o e volve t he d atabase schema.The b ootstrap c ommand h as n o p arameters. S o r unning i t i s a s s imple a s:/home/cbegin/testdb$ migrate bootstrapAs u sual, y ou c an u se t he -‐-‐path o ption t o s pecify t he r epository p ath, o therwise t he c urrent w orking directory i s a ssumed t o b e t he r oot o f y our m igration r epository (aka m igration p ath).If t here a re e nvironment s pecific e lements i n y our b ootstrap s cript, y ou’ll l earn l ater t hat y ou c an u se properties t o d eal w ith t hose.newNow t hat y ou’ve i nitialized y our r epository a nd b ootstrapped y our e xisting d atabase s chema, y ou’re ready t o s tart l everaging t he p ower o f M yBatis M igrations!MyBatis M igrations a re s imple S QL s cript f iles (*.sql) t hat l ive i n t he s cripts d irectory a nd f ollow a v ery strict c onvention. S ince t his c onvention i s s o i mportant, w e d on’t w ant t o l eave i t u p t o h umans t o t ry t o get i t r ight e very t ime… s o w e l et a utomation d o w hat i t d oes b est, a nd k eep t hings c onsistent.The n ew c ommand g enerates t he s keleton o f a m igration s cript t hat y ou c an t hen s imply f ill i n. T he command i s s imply r un a s f ollows:/home/cbegin/testdb$ migrate new “create blog table”The p arameter t hat t he n ew c ommand t akes i s a c omment d escribing t he m igration t hat y ou’re creating. Y ou d on’t n eed q uotes a round i t, b ut i t h elps k eep t he c ommand r eadable.When t he c ommand i s r un, i t w ill c reate a f ile n amed s omething l ike t he f ollowing: 20090807221754_create_blog_table.sqlThis f ormat i s v ery i mportant (which i s w hy i t’s g enerated). T he n umber a t t he b eginning p lays t hree roles. F ist, i t’s a p ractically u nique i dentifier, m eaning i t’s h ighly u nlikely t hat t wo p eople w ill g enerate the s ame o ne a t t he s ame t ime (it’s n ot a b ig d eal t o r esolve i f i t d oes h appen). S econd, i t’s a timestamp, i ndicating w hen t he m igration w as c reated. T hird, i t i s a n o rdinal i ndex, f ormatted i n a w ay that w ill k eep t he m igrations s orted i n t he o rder i n w hich t hey w ere c reated. T he r emainder o f t he filename i s t he c omment y ou s pecified i n t he p arameter. F inally, t he s uffix i s .sql, i ndicating t he f ile t ype that m ost e ditors w ill r ecognize.The c ontents o f t he m igration s cript a lso f ollows a s pecific a nd r equired p attern. H ere’s t he c ontents o f the f ile w e j ust g enerated:--// create blog table-- Migration SQL that makes the change goes here.--//@UNDO-- SQL to undo the change goes here.Notice t hat y our c omment o nce a gain a ppears a t t he t op o f t he f ile. Y ou c an a dd m ore c omments beneath i t a nd t hroughout t he s cript i f y ou l ike.The s ection i mmediately f ollowing t hat c omment i s w here y ou w ould p ut y our D DL c ommands t o c reate the b log t able.Then n otice t he -‐-‐//@UNDO s ection. T his s ection d emarcates t he s cript f ile s ections, s plitting i t i nto t wo distinct p arts. O nly t he c ommands a bove t he u ndo s ection w ill b e e xecuted w hen u pgrading a d atabase. Everything b eneath t he u ndo s ection w ill b e r un w hen d owngrading t he d atabase. B oth s ections a re kept i n t he s ame f ile f or s implicity a nd c larity. T he f ollowing i s a f illed i n s cript:--// create blog tableCREATE TABLE BLOG (ID INT,NAME VARCHAR(255),PRIMARY KEY(ID));--//@UNDODROP TABLE BLOG;Notice t hat t he c ommands a re t erminated b y a c olon. T his i s a lso i mportant, a nd y ou w ill r eceive a warning a nd l ikely a f ailure i f y ou d on’t t erminate t he S QL s tatements w ith a c olon.Optionally, y ou c an c onfigure y our o wn t emplate t o b e c onsumed b y t he ‘new’ c ommand. C onfiguration requires a f ile n amed m igrations.properties (in $MIGRATIONS_HOME). T his f ile w ill c ontain t he l ocation of y our t emplate.Example of migration.propertiesnew_command.template=templates/new_template_migration.sql Alternatively y ou c an m anually s pecify t he l ocation o f y our t emplate a s s uch:migrate new –template=<path to template> “your description”If n either o f t hese a re u sed, o r v alid, t he d efault t emplate s hown o n t he p revious p age w ill b e u sed.So h ow d o w e r un t his s cript? W ell, f irst i t’s p robably i mportant t o u nderstand t he c urrent s tate o f t he database.statusThe s tatus c ommand w ill r eport t he c urrent s tate o f t he d atabase. T he s tatus c ommand t akes n o parameters a nd o perates o n t he c urrent w orking d irectory o r t hat s pecified b y t he -‐-‐path o ption (as w ith all o ther c ommands)./home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 ...pending... create changelog20090804225328 ...pending... create blog tableSince w e’ve n ever r un a m igration, t he s tatus o f a ll o f t he e xisting m igration s cripts i s p ending, i ncluding the c hangelog t able i tself, w hich i s w here m ore d etailed s tatus l ogs a re k ept. O nce w e r un t he u p command (discussed n ext), t he s tatus w ill r eport s omething l ike t he f ollowing:/home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 2009-08-04 22:51:16 create changelog20090804225328 2009-08-04 22:51:16 create blog tableThanks t o o ur i dentifier f ormat, t hings a re i n o rder, a nd w e c an s ee w hen a m igration s cript w as c reated, as w ell a s w hen i t w as a pplied. T he c omment h elps u s r ead a h igh l evel o verview o f t he e volution o f t his database. A s w e a dd m igrations t his s tatus l og w ill g row. F or e xample:/home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 2009-08-04 22:51:16 create changelog20090804225207 2009-08-04 22:52:51 create author table 20090804225328 2009-08-04 22:54:33 create blog table20090804225333 2009-08-04 22:54:33 create post tableYou c an a lso g et t his i nformation f rom t he c hangelog t able b y q uerying i t d irectly i n t he d atabase. O f course, y ou w on’t s ee a ny “pending” i tems, a s t hose a re o nly k nown t o t he m igration r epository u ntil they’re a pplied t o t he d atabaseup, d ownAs d iscussed a bove, t he m igration s cripts h ave b oth a d o a nd a n u ndo s ection i n t hem. I t’s t herefore possible t o e volve a nd d evolve a d atabase t o s implify d evelopment a nd c oncurrent e volution o f t he database a cross d evelopment t eams. T he u p c ommand r uns t he d o s ection o f a ll p ending m igrations i n order, o ne a fter t he o ther. T he d own c ommand r uns t he u ndo s ection o f t he l ast a pplied m igration only. T hese c ommands b ehave t his w ay b ecause y ou’re m ost l ikely t o a lways w ant t he l atest r evision o f the d atabase s chema, a nd i f y ou e ver n eed t o r oll b ack, y ou’ll p robably o nly w ant t o d o s o f or t he l ast few v ersions – a nd d o s o i n a c ontrolled m anner.Here’s a m ore v isual e xample o f h ow t he u p a nd d own c ommands w ork. W e’ll u se t he s tatus c ommand in b etween t o s ee t he e ffect:/home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 ...pending... create changelog20090804225207 ...pending... create author table 20090804225328 ...pending... create blog table20090804225333 ...pending... create post table/home/cbegin/testdb$ migrate up/home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 2009-08-04 22:51:17 create changelog20090804225207 2009-08-04 22:51:17 create author table 20090804225328 2009-08-04 22:51:17 create blog table20090804225333 2009-08-04 22:51:17 create post table/home/cbegin/testdb$ migrate down/home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 2009-08-04 22:51:17 create changelog20090804225207 2009-08-04 22:51:17 create author table20090804225328 2009-08-04 22:51:17 create blog table20090804225333 ...pending... create post tableAs m entioned, b y d efault u p a pplies a ll p ending m igrations, a nd d own u ndoes j ust t he m ost r ecent o ne. Both u p a nd d own c ommands c an t ake a n i nteger p arameter t o o verride t hese d efaults. T he i nteger specifies h ow m any s teps s hould b e e xecuted. F or e xample:/home/cbegin/testdb$ migrate down 2/home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 2009-08-04 22:51:17 create changelog20090804225207 ...pending... create author table 20090804225328 ...pending... create blog table20090804225333 ...pending... create post tableThere r eally i sn’t m uch m ore t o t he u p a nd d own c ommands t han t hat. T hey l et y ou n avigate t he evolution o f t he d atabase s chema f orward a nd b ackward. A s u sual, t hey o perate o n t he r epository i n the c urrent w orking d irectory, o r t he o ne s pecified i n t he o ptiona -‐-‐path o ption.versionThe u p a nd d own c ommands a re p retty p rescriptive i n h ow t hey w ork. T he u p c ommand e volves a ll t he way u p, a nd d own o nly d evolves o ne s tep d own. S ometimes t hat m ight b e l imiting, s o t he v ersion command e xists t o a llow y ou t o m igrate t he s chema t o a ny s pecific v ersion o f t he d atabase y ou l ike. You s imply c all i t, s pecifying t he v ersion y ou’d l ike t o e nd u p a t, a nd t he m igrations s ystem f igures o ut whether i t h as t o g o u p o r d own, a nd w hich m igrations i t n eeds t o r un. H ere’s a n e xample./home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 ...pending... create changelog20090804225207 ...pending... create author table 20090804225328 ...pending... create blog table20090804225333 ...pending... create post table/home/cbegin/testdb$ migrate version 20090804225207/home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 2009-08-04 22:51:17 create changelog20090804225207 2009-08-04 22:51:17 create author table 20090804225328 ...pending... create blog table20090804225333 ...pending... create post table/home/cbegin/testdb$ migrate up/home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 2009-08-04 22:51:17 create changelog20090804225207 2009-08-04 22:51:17 create author table 20090804225328 2009-08-04 22:54:32 create blog table20090804225333 2009-08-04 22:54:32 create post table/home/cbegin/testdb$ migrate version 20090804225207/home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 2009-08-04 22:51:17 create changelog20090804225207 2009-08-04 22:51:17 create author table 20090804225328 ...pending... create blog table20090804225333 ...pending... create post tableThe v ersion c ommand i s a p owerful u tility f or m oving t o a s pecific r evision o f t he d atabase. pendingSometimes w hen w orking w ith a t eam o f p eople, o r w ith m ultiple t eams o f p eople, i t’s p ossible t hat more t han o ne c hange t o t he d atabase c an b e m ade a t a t ime. P ast s olutions t o t his p roblem h ave b een to c entralize t he m anagement o r r esponsibility f or c hange t o o ne p erson o r t eam. B ut t his c reates bureaucracy a nd s lows d own t he d evelopment p rocess. I t a lso h urts a utomation a nd c ontinuous integration. T herefore w e n eed a b etter a pproach. M yBatis M igrations s imply a llows t his s ituation t o occur, b ut m akes i t v ery o bvious t hat i t h as h appened. T hen t he t eams c an r eview t he s ituation, downgrade t heir s chemas a nd r e-‐run t he m igrations i n o rder, a nd r e-‐assess t he s ituation. I t a llows teams t o w ork a utonomously, w hile e ncouraging c ommunication, t eam w ork a nd g ood s ource c ontrol practices. W hen s omeone c reates m igration i n a nother w orkspace b efore y ou, b ut c ommits t o t he source c ontrol s ystem l ater t han y ou, y ou’ll e nd u p w ith a n o rphaned p ending m igration. T hey’re e asy to s pot w ith t he s tatus c ommand:/home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 2009-08-04 22:51:17 create changelog20090804225207 2009-08-04 22:51:17 create author table 20090804225328 ...pending... create blog table20090804225333 2009-08-04 22:51:17 create post tableMyBatis M igrations w ill n ot r un t his o rphaned m igration s imply b y r unning t he u p c ommand. I nstead, you’d h ave t o d owngrade t o t he p oint j ust b efore t he o rphaned m igration, t hen r un u p t o r un a ll o f t he migrations i n o rder. T his i s t he s afest a nd r ecommended a pproach.However, i f y ou a nd t he o ther t eam r eview t he c hange, a nd d ecide i t’s c ompletely i solated a nd n ot a conflicting c hange, t hen t here i s a w ay t o r un t he p ending m igration(s) o ut o f o rder. T he p ending command d oes j ust t hat. I t r uns a ll p ending m igrations r egardless o f t heir o rder o r p osition i n t he s tatus log. S o i f w e w ere t o r un t he p ending c ommand g iven t he s ituation a bove, t he r esults w ould b e a s w e expect:/home/cbegin/testdb$ migrate pending/home/cbegin/testdb$ migrate statusID Applied At Description================================================================== 20090802210445 2009-08-04 22:51:17 create changelog20090804225207 2009-08-04 22:51:17 create author table20090804225328 2009-08-05 24:55:23 create blog table20090804225333 2009-08-04 22:51:17 create post tableEven a fter t he f act, y ou’ll b e a ble t o i dentify a ny m igrations r un i n t his w ay, a s t he a pplied d ate w ill g ive them a way. A n o ut-‐of-‐order a pplied d ate i s c lear i ndication t hat a m igration w as r un o ut o f o rder. N o surprises!Some c ommands l ike p ending a nd d own a re h ighly u nlikely t o e ver b e n eeded i n p roduction. B y t he time y ou p romote m igrations t o p roduction, y ou’ve h opefully d ecided o n y our f inal s chema a nd t ested and a pproved t he s chema f or r elease. W hile t hey w on’t b e u sed i n p roduction, t hey a re h ighly v aluable during t he d evelopment p rocess. O nce y ou g et u sed t o t he i dea, y ou w on’t b e a ble t o w ork w ithout i t again.scriptWhile w e d evelopers w ish w e h ad u nlimited a ccess t o e very e nvironment, t he u nfortunate t ruth i s t hat we d on’t. O ften i t’s t he v ery p roduction e nvironment t hat w e’re t argeting t hat w e d on’t h ave a ccess t o. Someone e lse, a D BA o r C hange M anagement t eam w ill n eed t o a pply a ny c hanges. H owever, w e d on’t want t his t o b e a n e xcuse t o n ot u se a g ood, a utomated c hange m anagement t ool.MyBatis M igrations p rovides t he s cript c ommand t o g enerate a s cript t hat c an m igrate a s chema f rom one v ersion t o a nother. A s m entioned a bove, t his w ill l ikely a lways b e i n a n u pward d irection, b ut t he script c ommand d oes a lso s upport g enerating u ndo s cripts (just i n c ase y ou’re s o u nfortunate t hat y ou don’t e ven h ave a ccess t o c entral d evelopment d atabases!).The s cript c ommand i s q uite s imple. I t t akes t wo v ersion n umbers a s p arameters. T hink o f i t a s generating a s cript t o a pply a ll o f t he i dentified v ersions (inclusive) i n t he o rder s pecified. F or e xample, given t he f ollowing:/home/cbegin/testdb$ migrate statusID Applied At Description==================================================================。
MyBatis 3用户指南从文档中复制代码的警告对,这不是一个法律上的警告,但是它可以帮助你保持清醒的认识。
从美学上来讲,现代的文字处理工具在制作可读性强和格式良好的文本上做了大量的工作。
然而,它们也往往会由于插入特殊字符而完全破坏代码示例,有时看起来和你想要的是一模一样的。
“引号"和连字符就是一个很好的例子-在IDE 环境或文本编辑器中,左边的那个符号就不会正常起作用,至少不会是你想要的那个效果。
阅读本文档,就要享受它,希望它能对你有帮助。
当遇到代码段示例的时候,可以寻找示例和下载(包括单元测试等),或是来自网站和邮件列表的示例。
帮助我们把文档做得更好…如果你发现了本文档的遗漏之处,或者丢失My B at i s 特性的说明时,那么最好的方法就是了解一下这个遗漏之处然后把它记录下来。
我们在w i ki 接收公共的文档贡献:http://code.goo /p/myba t is/wiki/Welcome你也是本文档的最佳作者,其他用户也会来阅读它的。
关于翻译My B at i s 3 的用户指南翻译由南磊完成,若对翻译质量有任何意见和建议,请联系nanle i1987@gma i l.c o m,愿和大家共同提高,共同进步。
目录什么是MyBatis? (5)入门 (5)从XML 中构建SqlSessionFactory .............................................................................. 5 不使用XML 构建SqlSessionFactory (6)从SqlSessionFactory 中获取SqlSession (6)探究已映射的SQL 语句 (7)命名空间的一点注释.......................................................................................... 8 范围和生命周期.. (8)SqlSessionFactoryBu i ld e r (8)SqlSessionFactory (9)SqlSession (9)Mapper 实例 (9)XML 映射配置文件 (10)properties (10)Settings (11)typeAliases (12)typeHand l ers (13)objectFactory (14)plug i ns (15)environments (16)transactionManager (17)dataSsource (17)mappers (19)SQL 映射的XML 文件 (19)select (20)insert,update,delete (21)sql (23)Parameters (24)resultMap (25)高级结果映射 (27)id,result (29)支持的JDBC 类型............................................................................................ 30 构造方法.......................................................................................................... 30 关联................................................................................................................. 31 集合................................................................................................................. 34 鉴别器............................................................................................................. 36 缓存 (38)使用自定义缓存............................................................................................... 38 参照缓存.. (39)动态SQL (39)if (40)choose, w h en, otherw i se (40)trim, w h ere, set (41)foreach (43)Java API (43)应用目录结构 (43)SqlSessions (44)SqlSessionFactoryBu i ld e r (44)SqlSessionFactory (46)SqlSession (47)Select B uild e r (53)SqlBu i lder (56)什么是MyBatis?My Bat is 是支持普通SQL 查询,存储过程和高级映射的优秀持久层框架。
MyBatis用户指南中文版最近更新: 02 四月2013Version: 3.2.2PDF Creator :Esin.z2013/04/10内容目录MyBatis (1)简介 (3)什么是MyBatis? (3)Help make this documentation better (3)关于翻译 (3)入门 (3)从XML 中构建SqlSessionFactory (3)不使用XML 构建SqlSessionFactory (4)从SqlSessionFactory 中获取SqlSession (5)探究已映射的SQL 语句 (5)范围和生命周期 (7)XML 映射配置文件 (8)properties (9)settings (10)typeAliases (14)typeHandlers (15)Handling Enums (18)objectFactory (20)plugins (20)environments (21)databaseIdProvider (24)mappers (25)Mapper XML 文件 (26)select (27)insert, update and delete (28)sql (31)Parameters (32)Result Maps (33)Auto-mapping (49)缓存 (50)动态SQL (52)if (53)choose, when, otherwise (53)trim, where, set (54)foreach (56)bind (56)Multi-db vendor support (57)Pluggable Scripting Languages For Dynamic SQL (57)Java API (58)应用目录结构 (58)SqlSessions (59)Statement Builders (72)SelectBuilder (72)SqlBuilder (75)Logging (76)Logging Configuration (77)简介什么是 MyBatis?MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。
MyBatis 3 用户指南从文档中复制代码的警告对,这不是一个法律上的警告,但是它可以帮助你保持清醒的认识。
从美学上来讲,现代的文字处理工具在制作可读性强和格式良好的文本上做了大量的工作。
然而,它们也往往会由于插入特殊字符而完全破坏代码示例,有时看起来和你想要的是一模一样的。
“引号"和连字符就是一个很好的例子-在IDE环境或文本编辑器中,左边的那个符号就不会正常起作用,至少不会是你想要的那个效果。
阅读本文档,就要享受它,希望它能对你有帮助。
当遇到代码段示例的时候,可以寻找示例和下载(包括单元测试等),或是来自网站和邮件列表的示例。
帮助我们把文档做得更好…如果你发现了本文档的遗漏之处,或者丢失MyBatis特性的说明时,那么最好的方法就是了解一下这个遗漏之处然后把它记录下来。
我们在wiki接收公共的文档贡献:/p/mybatis/wiki/Welcome你也是本文档的最佳作者,其他用户也会来阅读它的。
关于翻译MyBatis 3的用户指南翻译由南磊完成,若对翻译质量有任何意见和建议,请联系nanlei1987@,愿和大家共同提高,共同进步。
目录什么是MyBatis? (5)入门 (5)从XML中构建SqlSessionFactory (5)不使用XML构建SqlSessionFactory (6)从SqlSessionFactory中获取SqlSession (6)探究已映射的SQL语句 (7)命名空间的一点注释 (8)范围和生命周期 (8)SqlSessionFactoryBuilder (8)SqlSessionFactory (9)SqlSession (9)Mapper实例 (9)XML映射配置文件 (10)properties (10)Settings (11)typeAliases (12)typeHandlers (13)objectFactory (14)plugins (15)environments (16)transactionManager (17)dataSsource (17)mappers (19)SQL映射的XML文件 (19)select (20)insert,update,delete (21)sql (23)Parameters (24)resultMap (25)高级结果映射 (27)id,result (29)支持的JDBC类型 (30)构造方法 (30)关联 (31)集合 (34)鉴别器 (36)缓存 (38)使用自定义缓存 (38)参照缓存 (39)动态SQL (39)if (40)choose, when, otherwise (40)trim, where, set (41)foreach (43)Java API (43)应用目录结构 (43)SqlSessions (44)SqlSessionFactoryBuilder (44)SqlSessionFactory (46)SqlSession (47)SelectBuilder (53)SqlBuilder (56)什么是MyBatis?MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。
MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。
MyBatis使用简单的XML 或注解用于配置和原始映射,将接口和Java的POJOs(Plan Old Java Objects,普通的Java 对象)映射成数据库中的记录。
入门每一个MyBatis的应用程序都以一个SqlSessionFactory对象的实例为核心。
SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象来获得。
SqlSessionFactoryBuilder对象可以从XML配置文件,或从Configuration类的习惯准备的实例中构建SqlSessionFactory对象。
从XML中构建SqlSessionFactory从XML文件中构建SqlSessionFactory的实例非常简单。
这里建议你使用类路径下的资源文件来配置,但是你可以使用任意的Reader实例,这个实例包括由文字形式的文件路径或URL形式的文件路径file://来创建。
MyBatis包含了一些工具类,称作为资源,这些工具类包含一些方法,这些方法使得从类路径或其他位置加载资源文件更加简单。
String resource = "org/mybatis/example/Configuration.xml";Reader reader = Resources.getResourceAsReader(resource);sqlMapper = new SqlSessionFactoryBuilder().build(reader);XML配置文件包含对MyBatis系统的核心设置,包含获取数据库连接实例的数据源和决定事务范围和控制的事务管理器。
关于XML配置文件的详细内容可以在文档后面找到,这里给出一个简单的示例:<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-////DTD Config 3.0//EN""/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文档正确性。
environment元素体中包含对事务管理和连接池的环境配置。
mappers元素是包含所有mapper(映射器)的列表,这些mapper 的XML文件包含SQL代码和映射定义信息。
不使用XML构建SqlSessionFactory如果你喜欢从Java程序而不是XML文件中直接创建配置实例,或创建你自己的配置构建器,MyBatis也提供完整的配置类,提供所有从XML文件中加载配置信息的选项。
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();TransactionFactory transactionFactory = newJdbcTransactionFactory();Environment environment =new Environment("development", transactionFactory, dataSource);Configuration configuration = new Configuration(environment);configuration.addMapper(BlogMapper.class);SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(configuration);注意这种情况下配置是添加映射类。
映射类是Java类,这些类包含SQL映射语句的注解从而避免了XML文件的依赖,XML映射仍然在大多数高级映射(比如:嵌套Join映射)时需要。
出于这样的原因,如果存在XML配置文件的话,MyBatis将会自动查找和加载一个对等的XML文件(这种情况下,基于类路径下的BlogMapper.class类的类名,那么BlogMapper.xml将会被加载)。
后面我们会了解更多。
从SqlSessionFactory中获取SqlSession现在,我们已经知道如何获取SqlSessionFactory对象了,基于同样的启示,我们就可以获得SqlSession的实例了。
SqlSession对象完全包含以数据库为背景的所有执行SQL操作的方法。
你可以用SqlSession实例来直接执行已映射的SQL语句。
例如:SqlSession session = sqlMapper.openSession();try {Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);} finally {session.close();}这种方法起到的作用,和我们使用之前的MyBatis版本是相似的,现在有一种更简洁的方法。
使用合理描述参数和SQL语句返回值的接口(比如BlogMapper.class),这样现在就可以至此那个更简单,更安全的代码,没有容易发生的字符串文字和转换的错误。
例如:SqlSession session = sqlSessionFactory.openSession();try {BlogMapper mapper = session.getMapper(BlogMapper.class);Blog blog = mapper.selectBlog(101);} finally {session.close();}现在我们来探究一下这里到底执行了什么。