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的注解的用法MyBatis的注解用法可以分为以下几个方面:1. 添加命名空间注解(@Mapper):在Mapper接口上使用@Mapper注解,将该接口标识为MyBatis的映射器接口,MyBatis会自动为它生成实现类。
2. 添加查询语句注解(@Select、@Insert、@Update、@Delete):在Mapper接口的方法上使用相应的注解,指定SQL语句,参数映射和结果映射等信息。
例如:```java@Select("SELECT * FROM user WHERE id = #{id}")User getUserById(int id);```3. 添加参数映射注解(@Param):在Mapper接口的方法参数上使用@Param注解,指定参数的名称,可以在SQL语句中通过该名称引用参数。
例如:```java@Select("SELECT * FROM user WHERE name = #{name} AND age = #{age}")User getUserByNameAndAge(@Param("name") String name, @Param("age") int age);```4. 添加结果映射注解(@Results、@Result):在Mapper接口的方法上使用@Results注解,指定返回结果的映射关系,可以通过@Result注解指定每个属性的映射关系。
例如:```java@Results({@Result(property = "id", column = "user_id"),@Result(property = "name", column = "user_name"),@Result(property = "age", column = "user_age")})@Select("SELECT * FROM user")List<User> getAllUsers();```5. 添加动态SQL注解(@If、@Choose、@When、@Otherwise):在Mapper接口的方法上使用动态SQL注解,根据条件动态生成SQL语句。
mybatis注解详解/mybatis-3/zh/sqlmap-xml.htmlmybatis的原⾝是ibatis,现在已经脱离了apache基⾦会,新官⽹是/。
mybatis3中增加了使⽤注解来配置Mapper的新特性,本篇⽂章主要介绍其中⼏个@Provider的使⽤⽅式,他们是:@SelectProvider、@UpdateProvider、@InsertProvider和@DeleteProvider。
中的最后⼀章描述了注解的简单⽤法,但是对于这⼏个Provider的具体使⽤⽅式并没有说的很清楚,特别是参数传递的⽅式,完全没有提及,对于初次使⽤的同学来说,会造成不⼩的困扰。
经过⼀些尝试后,我总结了⼀些Provider的使⽤经验,下⾯以@SelectProvider为例,依次描述⼏种典型的使⽤场景。
1.使⽤@SelectProvider@SelectProvider是声明在⽅法基本上的,这个⽅法定义在Mapper对应的的interface上。
1 public interface UserMapper {2 @SelectProvider(type = SqlProvider.class, method = "selectUser")3 @ResultMap("userMap")4 public User getUser(long userId);5 }上例中是个很简单的Mapper接⼝,其中定义了⼀个⽅法:getUser,这个⽅法根据提供的⽤户id来查询⽤户信息,并返回⼀个User实体bean。
这是⼀个很简单很常⽤的查询场景:根据key来查询记录并将结果封装成实体bean。
其中:@SelectProvider注解⽤于⽣成查询⽤的sql语句,有别于@Select注解,@SelectProvide指定⼀个Class及其⽅法,并且通过调⽤Class上的这个⽅法来获得sql语句。
mybatis3 typealias 例子-回复MyBatis 3 TypeAlias Example: Simplifying Java Type References for Smoother Database InteractionsMyBatis is a popular Java-based persistence framework that provides robust support for interacting with relational databases. One of the key features of MyBatis is the ability to map SQL queries and database results directly to Java objects, simplifying the process of working with databases in Java applications. In this article, we will explore the concept of type aliasing in MyBatis, which allows for easier and more concise references to Java types in your MyBatis configuration.To begin with, let's understand the need for type aliasing in MyBatis. In Java, when working with JDBC, we often need to write boilerplate code for mapping Java types to their corresponding JDBC types. This can be cumbersome and error-prone, especially when dealing with complex object hierarchies. MyBatis solves this problem by introducing the concept of type aliases.Type aliasing in MyBatis allows us to provide custom names for Java types, which can be used instead of fully qualified class namesthroughout the MyBatis configuration. This makes the configuration files more readable and helps prevent errors that can occur when manually typing fully qualified class names.To illustrate the usage of type aliasing, let's consider a simple example. Suppose we have a Java class called `User` that represents a user in our application. The fully qualified class name for `User` is `er`. In our MyBatis configuration file, instead of using the fully qualified class name every time we reference `User`, we can define a type alias as follows:xml<typeAliases><typeAlias type="er" alias="User"/></typeAliases>Now, we can refer to `User` simply as `User` throughout the configuration file. For example, instead of writing`<resultType="er">`, we can write`<resultType="User">`.Type aliases can also be used for mapper interfaces and their methods. For instance, if we have a mapper interface called`UserMapper` with a method named `getUserById`, we can define a type alias for the mapper interface as well:xml<typeAliases><typeAlias type="erMapper"alias="UserMapper"/></typeAliases>Now, the mapper interface can be referred to as `UserMapper` in the rest of the configuration file, reducing the verbosity and improving readability.Type aliases can also be defined for collections, which can be useful when working with complex object hierarchies. For example, suppose our `User` class has a property called `orders`, which is a list of `Order` objects. We can define a type alias for the collection as follows:xml<typeAliases><typeAlias type="java.util.List" alias="Orders"/></typeAliases>Now, whenever we need to refer to `List<Order>`, we can simply use `Orders`.In addition to explicitly defining type aliases in the MyBatis configuration file, MyBatis also provides built-in aliases for common Java types. These aliases can be used out of the box, without any additional configuration. Some of the most commonly used built-in aliases include `int` for `ng.Integer`, `long` for `ng.Long`, `map` for `java.util.Map`, and `list` for `java.util.List`, among others.It is worth mentioning that type aliases in MyBatis are case insensitive. This means that `User`, `user`, and `USER` will all refer to the same type alias defined as `User`.To summarize, type aliasing in MyBatis is a powerful feature thatsimplifies the process of working with Java types in MyBatis configuration files. By providing custom names for Java types, we can write more concise and readable configuration files, reducing the chances of errors. Whether defining type aliases explicitly in the configuration file or using the built-in aliases, type aliasing is a handy technique that enhances the overall experience of using MyBatis for database interactions in Java applications.。
MyBatis 3User GuideWarning about Copying Code from this DocumentNo, this is not a legal warning. It is one to help you keep your sanity. Modern word processors do a great job of making text readable and formatted in an aesthetically pleasing way. However, they also tend to completely ruin code examples byinserting special characters, sometimes that look exactly the same as the one youthink you want. “Quotes” and hyphens are a perfect example –the quotes andhyphen you see to the left will not work as quotes in an IDE or text editor, at leastnot the way you intend.So read this document, enjoy it and hopefully it is helpful to you. When it comes tocode examples, seek out the examples included with the download (including unittests etc.), or examples from the website or mailing list.Help make this documentation better…If you find this documentation lacking in any way, or missing documentation for a feature, then the best thing to do is learn about it and then write the documentation yourself!We accept public documentation contributions through our wiki at:/confluence/oss/display/IBATIS/Contribute+Doc umentationYou’re the best author of this documentation, people like you have to read it! ContentsWhat isMyBatis? ........................................................................................................................... .. (5)GettingStarted .............................................................................................................................. (5)Building SqlSessionFactory fromXML (5)Building SqlSessionFactory withoutXML (6)Acquiring a SqlSession fromSqlSessionFactory (6)Exploring Mapped SQLStatements (7)A Note about Namespaces (8)Scope andLifecycle ........................................................................................................................... . (9)Mapper ConfigurationXML (10)properties ......................................................................................................................... . (11)settings ............................................................................................................................. . (12)typeAliases ........................................................................................................................ (13)typeHandlers .................................................................................................................... . (14)objectFactory .................................................................................................................. .. (15)plugins ............................................................................................................................... (16)environments .................................................................................................................... (17)transactionManager ........................................................................................................ .. (18)dataSource ....................................................................................................................... (19)mappers ............................................................................................................................ (21)SQL Map XMLFiles ................................................................................................................................... .. 21select ................................................................................................................................. (22)insert, update,delete ..............................................................................................................................24sql ...................................................................................................................................... (26)Parameters ...................................................................................................................... .. (26)MyBatis 3 - User Guide29 May 2010 4resultMap .......................................................................................................................... (28)Advanced ResultMapping (30)id,result ................................................................................................................................. (32)Supported JDBCTypes (33)constructor ....................................................................................................................... (33)association ........................................................................................................................ .. (34)collection ........................................................................................................................... .. (37)discriminator ..................................................................................................................... .. (40)cache ................................................................................................................................. (41)Using a CustomCache (43)cache-ref ......................................................................................................................... .. (44)DynamicSQL ................................................................................................................................... .. (44)if ........................................................................................................................................ (44)choose, when,otherwise ........................................................................................................................45trim, where,set ......................................................................................................................................45foreach ............................................................................................................................. . (47)JavaAPI ..................................................................................................................................... .. (49)DirectoryStructure .......................................................................................................................... (49)SqlSessions ....................................................................................................................... . (50)SqlSessionFactoryBuilder ................................................................................................ .. (50)SqlSessionFactory............................................................................................................. (52)SqlSession ......................................................................................................................... (54)SelectBuilder ..................................................................................................................... . (60)SqlBuilder .......................................................................................................................... . (63)MyBatis 3 - User Guide29 May 2010 5What is MyBatis?MyBatis is a first class persistence framework with support for custom SQL, stored procedures andadvanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parametersand retrieval of results. MyBatis can use simple XML or Annotations for configuration and mapprimitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.Getting StartedEvery MyBatis application centers around an instance of SqlSessionFactory. A SqlSessionFactoryinstance can be acquired by using the SqlSessionFactoryBuilder. SqlSessionFactoryBuilder can build aSqlSessionFactory instance from an XML configuration file, of from a custom prepared instance of theConfiguration class.Building SqlSessionFactory from XMLBuilding a SqlSessionFactory instance from an XML file is very simple. It is recommended that you use aclasspath resource for this configuration, but you could use any Reader instance, including one createdfrom a literal file path or a file:// URL. MyBatis includes a utility class, called Resources, that contains anumber of methods that make it simpler to load resources from the classpath and other locations.String resource = "org/mybatis/example/Configuration.xml";Reader reader = Resources.getResourceAsReader(resource);sqlMapper = new SqlSessionFactoryBuilder().build(reader);The configuration XML file contains settings for the core of the MyBatis system, including a DataSourcefor acquiring database Connection instances, as well as a TransactionManager for determining howtransactions should be scoped and controlled. The full details of the XMLconfiguration file can be foundlater in this document, but here is a simple example:<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-////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>MyBatis 3 - User Guide29 May 2010 6While there is a lot more to the XML configuration file, the above example pointsout the most criticalparts. Notice the XML header, required to validate the XML document. The body of the environmentelement contains the environment configuration for transaction management and connection pooling.The mappers element contains a list of mappers –the XML files that contain the SQL code and mappingdefinitions.Building SqlSessionFactory without XMLIf you prefer to directly build the configuration from Java, rather than XML, or create your ownconfiguration builder, MyBatis provides a complete Configuration class that provides all of the sameconfiguration options as the XML file.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);Notice in this case the configuration is adding a mapper class. Mapper classes are Java classes thatcontain SQL Mapping Annotations that avoid the need for XML. However, due to some limitations ofJava Annotations and the complexity of some MyBatis mappings, XML mapping is still required for themost advanced mappings (e.g. Nested Join Mapping). For this reason, MyBatis will automatically lookfor and load a peer XML file if it exists (in this case, BlogMapper.xml would be loaded based on theclasspath and name of BlogMapper.class). More on this later.Acquiring a SqlSession from SqlSessionFactoryNow that you have a SqlSessionFactory, as the name suggests, you can acquire an instance ofSqlSession. The SqlSession contains absolutely every method needed to execute SQL commands againstthe database. You can execute mapped SQL statements directly against the SqlSession instance. Forexmaple:SqlSession session = sqlMapper.openSession();try {Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);} finally {session.close();}While this approach works, and is familiar to users of previous versions of MyBatis, there is now acleaner approach. Using an interface (e.g. BlogMapper.class) that properly describes the parameter andreturn value for a given statement, you can now execute cleaner and more type safe code, without errorprone string literals and casting.MyBatis 3 - User Guide29 May 2010 7For example:SqlSession session = sqlSessionFactory.openSession();try {BlogMapper mapper = session.getMapper(BlogMapper.class);Blog blog = mapper.selectBlog(101);} finally {session.close();}Now let's explore what exactly is being executed here.Exploring Mapped SQL StatementsAt this point you may be wondering what exactly is being executed by the SqlSession or Mapper class.The topic of Mapped SQL Statements is a big one, and that topic will likely dominate the majority of thisdocumentation. But to give you an idea of what exactly is being run, here are a couple of examples.In either of the examples above, the statements could have been defined by either XML or Annotations.Let's take a look at XML first. The full set of features provided by MyBatis can be realized by using theXML based mapping language that has made MyBatis popular over the years. If you've used MyBatisbefore, the concept will be familiar to you, but there have been numerous improvements to the XMLmapping documents that will become clear later. Here is an example of an XML based mappedstatement that would satisfy the above SqlSession calls.<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-////DTD Mapper 3.0//EN""/dtd/mybatis-3-mapper.dtd"><mapper namespace="org.mybatis.example.BlogMapper"><select id="selectBlog" parameterType="int" resultType="Blog">select * from Blog where id = #{id}</select></mapper>While this looks like a lot of overhead for this simple example, it is actually very light. You can define asmany mapped statements in a single mapper XML file as you like, so you get a lot of milage out of theXML header and doctype declaration. The rest of the file is pretty self explanatory. It defines a name forthe mapped statement “selectBlog”, in the namespace“org.mybatis.example.BlogMapper”, whichwould allow you to call it by specifying the fully qualified name of“org.mybatis.example.BlogMapper.selectBlog”, as we did above in the following example:Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);Notice how similar this is to calling a method on a fully qualified Java class, and there's a reason for that.This name can be directly mapped to a Mapper class of the same name as the namespace, with aMyBatis 3 - User Guide29 May 2010 8method that matches the name, parameter, and return type as the mapped select statement. Thisallows you to very simply call the method against the Mapper interface as you sawabove, but here it isagain in the following example:BlogMapper mapper = session.getMapper(BlogMapper.class);Blog blog = mapper.selectBlog(101);The second approach has a lot of advantages. First, it doesn't depend on a string literal, so it's muchsafer. Second, if your IDE has code completion, you can leverage that when navigating your mappedSQL statements. Third, you don't need to cast the return type, as the BlogMapper interface can haveclean, typesafe return types (and a typesafe parameter).A Note about Namespaces_ Namespaces were optional in previous versions of MyBatis, which was confusing and unhelpful. Namespaces are now required and have a purpose beyond simply isolating statements with longer, fully-qualified names.Namespaces enable the interface bindings as you see here, and even if you don’t think you’ll use them today, you should follow these practices laid out here in case you change your mind. Using the namespace once, and putting it in a proper Java package namespace will clean up your code and improve the usability of MyBatis in the long term._ Name Resolution: To reduce the amount of typing, MyBatis uses the following name resolution rules for all named configuration elements, including statements, result maps, caches, etc.Fully qualified names (e.g. “com.mypackage.MyMapper.selectAllThings”) are looked up directly and used if found.Short names (e.g. “selectAllThings”) can be used to reference any unambiguous entry. However if there are two or more (e.g. “com.foo.selectAllThings andcom.bar.selectAllThings”), then you will receive an error reporting that the short name is ambiguous and therefore must be fully qualified.There's one more trick to Mapper classes like BlogMapper. Their mapped statements don't need to bemapped with XML at all. Instead they can use Java Annotations. For example, the XML above could beeliminated and replaced with:package org.mybatis.example;public interface BlogMapper {@Select("SELECT * FROM blog WHERE id = #{id}")Blog selectBlog(int id);}MyBatis 3 - User Guide29 May 2010 9The annotations are a lot cleaner for simple statements, however, Java Annotations are both limited andmessier for more complicated statements. Therefore, if you have to do anything complicated, you'rebetter off with XML mapped statements.It will be up to you and your project team to determine which is right for you, and how important it is toyou that your mapped statements be defined in a consistent way. That said, you're never locked into asingle approach. You can very easily migrate Annotation based Mapped Statements to XML and viceversa.Scope and LifecycleIt's very important to understand the various scopes and lifecycles classes we've discussed so far. Usingthem incorrectly can cause severe concurrency problems. SqlSessionFactoryBuilderThis class can be instantiated, used and thrown away. There is no need to keep it around once you'vecreated your SqlSessionFactory. Therefore the best scope for instances of SqlSessionFactoryBuilder ismethod scope (i.e. a local method variable). You can reuse the SqlSessionFactoryBuilder to buildmultiple SqlSessionFactory instances, but it's still best not to keep it around to ensure that all of the XMLparsing resources are freed up for more important things. SqlSessionFactoryOnce created, the SqlSessionFactory should exist for the duration of your application execution. Thereshould be little or no reason to ever dispose of it or recreate it. It's a best practice to not rebuild theSqlSessionFactory multiple times in an application run. Doing so should be considered a “bad smell”.Therefore the best scope of SqlSessionFactory is application scope. This can be achieved a number ofways. The simplest is to use a Singleton pattern or Static Singleton pattern. However, neither of thoseis widely accepted as a best practice. Instead, you might prefer to investigate a dependency injectioncontainer such as Google Guice or Spring. Such frameworks will allow you to create providers that willmanage the singleton lifecycle of SqlSessionFactory for you.SqlSessionEach thread should have its own instance of SqlSession. Instances of SqlSession are not to be sharedand are not thread safe. Therefore the best scope is request or method scope. Never keep referencesto a SqlSession instance in a static field or even an instance field of a class. Never keep references to aSqlSession in any sort of managed scope, such as HttpSession of of the Servlet framework. If you'reusing a web framework of any sort, consider the SqlSession to follow a similar scope to that of an HTTPrequest. In other words, upon recieving an HTTP request, you can open a SqlSession, then uponreturning the response, you can close it. Closing the session is very important. You should alwaysMyBatis 3 - User Guide29 May 2010 10ensure that it's closed within a finally block. The following is the standard pattern for ensuring thatSqlSessions are closed:SqlSession session = sqlSessionFactory.openSession();try {// do work} finally {session.close();}Using this pattern consistently throughout your code will ensure that all database resources are properlyclosed (assuming you did not pass in your own connection, which is an indication to MyBatis that youwish to manage your own connection resources).Mapper InstancesMappers are interfaces that you create to bind to your mapped statements.Instances of the mapperinterfaces are acquired from the SqlSession. As such, technically the broadest scope of any mapperinstance is the same as the SqlSession from which they were requestsd. However, the best scope formapper instances is method scope. That is, they should be requested within the method that they areused, and then be discarded. They do not need to be closed explicitly. While it's not a problem to keepthem around throughout a request, similar to the SqlSession, you might find that managing too manyresources at this level will quickly get out of hand. Keep it simple, keep Mappers in the method scope.The following example demonstrates this practice.SqlSession session = sqlSessionFactory.openSession();try {BlogMapper mapper = session.getMapper(BlogMapper.class);// do work} finally {session.close();}Mapper Configuration XMLThe MyBatis XML configuration file contains settings and properties that have a dramatic effect on howMyBatis behaves. The high level structure of the document is as follows:configurationo propertieso settingso typeAliaseso typeHandlerso objectFactoryo pluginso environmentsMyBatis 3 - User Guide29 May 2010 11_ environmenttransactionManagerdataSourceo mapperspropertiesThese are externalizable, substitutable properties that can be configured in a typical Java Properties fileinstance, or passed in through sub-elements of the properties element. For example:<properties resource="org/mybatis/example/config.properties"><property name="username" value="dev_user"/><property name="password" value="F2Fa3!33TYyg"/></properties>The properties can then be used throughout the configuration files to substitute values that need to bedynamically configured. For example:<dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource>The username and password in this example will be replaced by the values set in the propertieselements. The driver and url properties would be replaced with values contained from theconfig.properties file. This provides a lot of options for configuration.Properties can also be passed into the SqlSessionBuilder.build() methods. For example:SqlSessionFactory factory =sqlSessionFactoryBuilder.build(reader, props);// ... or ...SqlSessionFactory factory =sqlSessionFactoryBuilder.build(reader, environment, props);If a property exists in more than one of these places, MyBatis loads them in the following order:Properties specified in the body of the properties element are read first,Properties loaded from the classpath resource or url attributes of the properties element areread second, and override any duplicate properties already specified ,Properties passed as a method parameter are read last, and override any duplicate propertiesthat may have been loaded from the properties body and the resource/url attributes.Thus, the highest priority properties are those passed in as a method parameter, followed byresource/url attributes and finally the properties specified in the body of the properties element.MyBatis 3 - User Guide29 May 2010 12settingsThese are extremely important tweaks that modify the way that MyBatis behaves at runtime. Thefollowing table describes the settings, their meanings and their default values. Setting Description Valid Values DefaultcacheEnabled Globally enables or disables any cachesconfigured in any mapper under thisconfiguration.true | false truelazyLoadingEnabled Globally enables or disables lazy loading.When disabled, all associations will be eagerlyloaded.true | false trueaggressiveLazyLoading When enabled, an object with lazy loadedproperties will be loaded entirely upon a callto any of the lazy properties. Otherwise, eachproperty is loaded on demand.true | false truemultipleResultSetsEnabled Allows or disallows multiple ResultSets to bereturned from a single statement (compatibledriver required).true | false trueuseColumnLabel Uses the column label instead of the columnname. Different drivers behave differently inthis respect. Refer to the driverdocumentation, or test out both modes todetermine how your driver behaves.true | false trueuseGeneratedKeys Allows JDBC support for generated keys. Acompatible driver is required. This settingforces generated keys to be used if set totrue, as some drivers deny compatibility butstill work (e.g. Derby).true | false FalseautoMappingBehavior Specifies if and how MyBatis shouldautomatically map columns tofields/properties. PARTIAL will only automapsimple, non-nested results. FULL willauto-map result mappings of any complexity(nested or otherwise).NONE,PARTIAL,FULLPARTIALdefaultExecutorType Configures the default executor. SIMPLEexecutor does nothing special. REUSEexecutor reuses prepared statements. BATCHexecutor reuses statements and batchesupdates.SIMPLEREUSEBATCHSIMPLEdefaultStatementTimeout Sets the timeout that determines how longthe driver will wait for a response from thedatabase.Any positiveintegerNot Set(null)An example of the settings element fully configured is as follows:<settings><setting name="cacheEnabled" value="true"/>MyBatis 3 - User Guide29 May 2010 13<setting name="lazyLoadingEnabled" value="true"/><setting name="multipleResultSetsEnabled" value="true"/><setting name="useColumnLabel" value="true"/><setting name="useGeneratedKeys" value="false"/><setting name="enhancementEnabled" value="false"/><setting name="defaultExecutorType" value="SIMPLE"/><setting name="defaultStatementTimeout" value="25000"/></settings>typeAliasesA type alias is simply a shorter name for a Java type. It's only relevant to the XML configuration andsimply exists to reduce redundant typing of fully qualified classnames. For example: <typeAliases><typeAlias alias="Author" type="domain.blog.Author"/><typeAlias alias="Blog" type="domain.blog.Blog"/><typeAlias alias="Comment" type="ment"/><typeAlias alias="Post" type="domain.blog.Post"/><typeAlias alias="Section" type="domain.blog.Section"/><typeAlias alias="Tag" type="domain.blog.Tag"/></typeAliases>With this configuration, “Blog”can now be used anywhere that“domain.blog.Blog”could be.There are many built-in type aliases for common Java types. They are all case。
DD WRT大家好,我是中国无线论坛的zmsky ,昨天我的850G 到了,用了下DD 感觉还行,发现对于新手来言,设置起来还是有点难得,今天我来讲一下DDWRT 的设置及功能讲解的设置及功能讲解先说句题外话moto 850g v2总体来说还行总体来说还行 价格便宜价格便宜 就是发热量大就是发热量大但是我昨天挂了一晚上的BT 没见死机,推荐大家购买,当然买思科的WRT54G v3.1更好更好首先把路由接通电源,第1次用建议按下路由背后的reset ,当路由启动好后,把网线分别查到路由后面的LAN 口上【别查到W AN 口】口】 另一头插计算机的网卡。
另一头插计算机的网卡。
一切就绪后一切就绪后 等待分配到IP 地址地址 分配到了后分配到了后 右下角应该能弹出个泡右下角应该能弹出个泡 本地连接本地连接已连接 有些电脑是直接消失掉,这里我们双击右下角那个网络连接有些电脑是直接消失掉,这里我们双击右下角那个网络连接 然后找到支持然后找到支持记录下后面的网关IP ,然后启动IE 浏览器浏览器 【必须IE !!!】地址栏那里输入网关IP地址栏那里输入网关IP 默认192.168.1.1 进去后随便点个选项进去后随便点个选项 他让你输入账号密码他让你输入账号密码 或者首次进去或者首次进去他让你设置账号密码user 用户用户 password 密码密码 默认用户密码是root admin 登陆成功后登陆成功后点administration 下面有个language selection 然后按右边的小箭头 选择chines simplified选择好了后按下面的 apply settings 保存完了后路由会重启保存完了后路由会重启 这个时候把IE关掉 待路由器重启完毕后在进网关待路由器重启完毕后在进网关OK 一切中文了一切中文了这里先设置下这里先设置下 管理里面管理里面 自行改用户密码接着进入自行改用户密码接着进入 设置设置设置路由的IP 可以安装我这样设置可以安装我这样设置 但是别设置成192.168.1.1 然后点下面的应用然后点下面的应用 等路由重启,然后用用刚刚设置的IP 来访问来访问接着进入应用程序&游戏找到Upnp全部启动全部启动 然后然后 应用应用然后找到DMZ输入自己的IP 在网络连接支持里面的IP 地址那栏能看到地址那栏能看到然后应用然后应用 OK设置差不多完了OK设置差不多完了 现在来讲功能现在来讲功能功能篇功能篇一、访问点(AP 、无线路由器模式)——最基本的功能!工作在访问点模式,和普通的无线路由器是一样的,既可当路由,又可做为纯AP 使用,支持802.11g 54MBps 的无线网卡接入。
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 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();}现在我们来探究一下这里到底执行了什么。