??xml version="1.0" encoding="utf-8" standalone="yes"?>精品国产999,在线小视频网址,国产精品性做久久久久久http://www.aygfsteel.com/alexprefect/category/51264.htmlzh-cnSat, 31 Mar 2012 00:36:29 GMTSat, 31 Mar 2012 00:36:29 GMT60Mybatis SQL映射文gQ{载)http://www.aygfsteel.com/alexprefect/articles/372968.htmlalexprefectalexprefectThu, 29 Mar 2012 03:08:00 GMThttp://www.aygfsteel.com/alexprefect/articles/372968.htmlhttp://www.aygfsteel.com/alexprefect/comments/372968.htmlhttp://www.aygfsteel.com/alexprefect/articles/372968.html#Feedback0http://www.aygfsteel.com/alexprefect/comments/commentRss/372968.htmlhttp://www.aygfsteel.com/alexprefect/services/trackbacks/372968.html前面学习的都是一些配|,mybatis的精华也集中在SQL的映文件上Q相比实现相同功能的jdbc代码Q节U了95%的代码量?/p>


<!-- 配置l定命名I间的缓?-->
<cache></cache>

<!-- 从其他命名空间引用缓存配|?-->
<cache-ref namespace="" />

<!-- 描述如何db中查询的l果集加载成对象 -->
<resultMap type="" id="">
<constructor>
<idArg />
<arg />
<arg />
<arg />
</constructor>
</resultMap>

<!-- 定义可重用的sql语句 -->
<sql id=""></sql>

<!-- 映射dml语句 -->
<insert id=""></insert>
<select id=""></select>
<update id=""></update>
<delete id=""></delete>



一、select可以可以说是使用最多的元素Q用也很简?/p>

 

  1. <select id="getUserById" parameterType="int" resultType="User"> 
  2.     select * from tbl_user where id = #{id} 
  3. </select> 

< select>元素中的一些属?U色为用的较多的属?

 

id 在命名空间中唯一的标识符Q可以被用来引用q条语句
parameterType会传入q条语句的参数类的完全限定名或别名?/td>
resultType 从这条语句中q回的期望类型的cȝ完全限定名或别名?br />意集合情形,那应该是集合可以包含的类型,
而不能是集合本n。?resultType?resultMapQ?br />但不能同时?/span>。(可以是基本类型int{,
复合cdUserQ集合类型map,list{)
resultMap 命名引用外部的resultMap。返回map是MyBat is
最具力量的Ҏ,对其有一个很好的理解的话Q?br />多复杂映的情Şp被解决了?br />使用 resultMap 或resultTypeQ但不能同时使用?/td>
flushCache 其讄?trueQ不句什么时候被带哦用,
都会D~存被清I。默认|false
useCache 其讄?trueQ将会导致本条语句的l果被缓存?br />默认|true
timeout  q个讄驱动E序{待数据库返回请求结果,q抛?br />异常旉的最大等待倹{默认不讄Q驱动自行处理)
fetchSize q是暗示驱动E序每次扚wq回的结果行数?br />默认不设|(驱动自行处理Q?/td>
statementType STATEMENT,PREPARED ?CALLABLE 的一U?br />q会?MyBat is使用选择使用
StatementQPreparedStatement?CallableStatement?br />默认|PREPARED?/td>
resultSetTypeFORWARD_ONLYQ?br />SCROLL_SENSITIVEQ?br />SCROLL_INSENSITIVE中的一U?br />默认是不讄Q驱动自行处理)

 

二、insert插入数据库,q行插入操作时主要是要拿到插入数据自增的主键

id 在命名空间中唯一的标识符Q可以被用来引用q条语句?/td>
parameterType
会传入q条语句的参数类的完全限定名或别?/td>
flushCache 其讄?trueQ不句什么时候被带哦用,都会D~存被清I。默认|false?/td>
timeoutq个讄驱动E序{待数据库返回请求结果,q抛出异常时间的最大等待倹{?br />默认不设|(驱动自行处理Q?
statementTypeSTATEMENT,PREPARED ?CALLABLE 的一U。这会让 MyBat is使用选择使用
StatementQPreparedStatement ?CallableStatement。默认|PREPARED?
useGeneratedKeysQ?span style="color: rgb(255, 0, 0);">仅对 insert ??/span> Q?q????MyBat is 使用 JDBC 的getGeneratedKeys Ҏ来取出由数据Q比如:?MySQL ?SQL Server q样的数据库理pȝ的自动递增字段Q内部生成的主键。默认|false?/td>
keyPropertyQ?span style="color: rgb(255, 0, 0);">仅对insert有用Q?标记一个属性, MyBat is会通过getGeneratedKeys或者通过 insert 语句的selectKey 子元素设|它的倹{默认:不设|?/td>

 

在进行insertQupdate,delete之后session要进行commit操作Q不然数据库不会更新到数据库

insert的Demo

另一U获取主键的Ҏ

  1. <insert id="addUserLastId" parameterType="User"> 
  2.     <selectKey resultType="int" order="AFTER" keyProperty="id"> 
  3.         SELECT LAST_INSERT_ID() AS id 
  4.     </selectKey> 
  5.     insert into tbl_user(name,age) values(#{name},#{age}) 
  6. </insert> 


 


  1. <insert id="addUser" parameterType="User" keyProperty="id" useGeneratedKeys="true" > 
  2.     insert into tbl_user(name,age) values(#{name},#{age}) 
  3. </insert> 
  1. @Test 
  2. public void testInsert() throws IOException { 
  3.     UserMapper mapper = session.getMapper(UserMapper.class) ;  
  4.     User user = new User() ; 
  5.     user.setName("zhangss") ; 
  6.     user.setAge(22) ; 
  7.     int i = mapper.addUser(user) ; 
  8.     session.commit() ; 
  9.     session.close() ; 
  10.     System.out.println("id:"+i+"--"+user.getId()); 


update的Demo

 

  1. <update id="updateUser" parameterType="User"> 
  2.     update tbl_user set name = #{name} ,age = #{age} where id = #{id} 
  3. </update> 

  1. @Test 
  2. public void testUpdate(){ 
  3.     UserMapper mapper = session.getMapper(UserMapper.class) ;  
  4.     User user = new User() ; 
  5.     user.setId(27) ; 
  6.     user.setName("zhang27") ; 
  7.     user.setAge(227) ; 
  8.     int i = mapper.updateUser(user) ; 
  9.     session.commit() ; 
  10.     session.close() ; 
  11.     System.out.println("id:"+i+"--"+user.getId()); 


三、sql定义可重用的sql语句

  1. <sql id="selectItem">id,name,age</sql> 

 


  1. <select id="getUserById" parameterType="int" resultType="User"> 
  2.      
  3.     <!--
  4.     select * from tbl_user where id = #{id}
  5.      --> 
  6.      select <include refid="selectItem"/> from tbl_user where id = #{id} 
  7. </select> 


四、Parameter


#{department, mode=OUT, jdbcType=CURSOR, javaType=ResultSet,resultMap=departmentResultMap}


 

五、resultMap所做的工作是从数据库中获取的ResultSetl果集放入指定的对象中,避免大量的setter getter代码Q实现自动装配的功能Q实现结果的映射


1、简单映?/p>

  1. <select id=”selectUsers” parameterType=”int” resultType=”hashmap”>  
  2.     select id, username, hashedPassword from some_table where id = #{id}  
  3. </select>  

所有列被自动映到 HashMap 的键上,key为列名,value为数据库中的数据

 


  1. <select id=”selectUsers” parameterType=”int” resultType=”com.someapp.model.User”>  
  2.     select id, username, hashedPassword from some_table where id = #{id}  
  3. </select>  

所有从数据库中取得数据自动装配到JavaBean中,如果列名与属性名相同Q则无需作Q务的q预卛_完成装配?p> 

如果数据库中的列名与javabean的属性名UC同可以在查询的时候取别名Q如

  1. <select id=”selectUsers” parameterType=”int” resultType=”User”>  
  2.     select user_id as “id”, user_name as “userName”, hashed_password as “hashedPassword”  from some_table where id = #{id}  
  3. </select>  

也可以用resultMapq行映射的指?p> 

  1. <resultMap id="userResultMap" type="User">  
  2.     <id property="id" column="user_id" />  
  3.     <result property="username" column="username"/>  
  4.     <result property="password" column="password"/>  
  5. </resultMap>  
  6.  
  7. <select id=”selectUsers” parameterType=”int”  resultMap=”userResultMap”>  
  8.     select user_id, user_name, hashed_password from some_table where id = #{id}  
  9. </select>  


 

2、resultMap高映射




alexprefect 2012-03-29 11:08 发表评论
]]>
Mybatis 配置文gQ{载)http://www.aygfsteel.com/alexprefect/articles/372967.htmlalexprefectalexprefectThu, 29 Mar 2012 03:07:00 GMThttp://www.aygfsteel.com/alexprefect/articles/372967.htmlhttp://www.aygfsteel.com/alexprefect/comments/372967.htmlhttp://www.aygfsteel.com/alexprefect/articles/372967.html#Feedback0http://www.aygfsteel.com/alexprefect/comments/commentRss/372967.htmlhttp://www.aygfsteel.com/alexprefect/services/trackbacks/372967.htmlq篇文章学习的是mybatis的主配置文gConfiguration.xmlQ这个配|文件主要配|一些全局的属性,如数据库的连接,cȝ别名Q不同的

场景q行不同的配|等{?/p>


一、Configuration.xml中可以配|的所有内?/p>


configuration 配置
properties 属?/td>
settings 讄
typeAliases cd命名
typeHandlers cd处理?
objectFactory 对象工厂
plugins 插g
environments 环境
environment 环境变量
transactionManager 事务理?
dataSource 数据?
映射?/span>

 



二、Properties标签

可以用来引用外部的属性文件进行配|,比如所有的配置都在一个eas.properties中配|,只需要在properties中配|一ơ,可以做Cơ配|到处引用?/p>

如现在配|一个eas.properties

 

  1. #db config 
  2. db.driver:com.sybase.jdbc3.jdbc.SybDriver 
  3. db.url:jdbc:sybase:Tds:192.168.2.143:2678/SMM_win2k8_portal 
  4. db.username:dba 
  5. db.password:smmsql 
  6.  
  7. #server config 
  8. server.url:http://192.168.2.101:8080/EAS 

在configuration.xml中对属性文件中的D行引?p> 

 

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd"> 
  4. <configuration> 
  5.     <properties resource="eas.properties" /> 
  6.      
  7.     <environments default="development"> 
  8.         <environment id="development"> 
  9.             <transactionManager type="JDBC"/> 
  10.             <dataSource type="POOLED"> 
  11.                 <property name="driver" value="${db.driver}"/> 
  12.                 <property name="url" value="${db.url}"/> 
  13.                 <property name="username" value="${db.username}"/> 
  14.                 <property name="password" value="${db.password}"/> 
  15.             </dataSource> 
  16.         </environment> 
  17.     </environments> 
  18. </configuration> 


 

三、Setteing标签Q对mybatis的一些行行设|?/p>



配置

<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="enhancementEnabled" value="false"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25000"/>
< /settings>


四、typeAliases Zc设|别名,方便书写


  1. <typeAliases> 
  2.     <!-- simple alias for full class name --> 
  3.     <typeAlias alias="App" type="com.justsy.eas.domain.App"/> 
  4.     <typeAlias alias="Content" type="com.justsy.eas.domain.Content"/> 
  5.     <typeAlias alias="AppDevice" type="com.justsy.eas.domain.AppDevice"/> 
  6.     <typeAlias alias="ListApp" type="com.justsy.eas.http.domain.ListApp"/> 
  7.     <typeAlias alias="ClientApp" type="com.justsy.eas.http.domain.ClientApp"/> 
  8. </typeAliases> 

java 中一些简单类型的别名

 

别名  映射的类?
_byte  byte
_long  long
_short  short
_int   int 
_integer   int 
_double  double
_float   float 
_boolean  boolean
string  String
byte  Byte
long  Long
short  Short
int   Integer
integer   Integer
double  Double
float   Float 
boolean  Boolean
date  Date
decimal  BigDecimal
bigdecimal  BigDecimal
object  Object
map  Map
hashmap  HashMap
list  List 
arraylist  ArrayList
collection  Collection
iterator  Iterator


五、typeHandlers 的作用是Javacd与数据库中类型进行匹配,在statement讑ր和ResultSet索值时可以正确的{换,可以实现TypeHandler接口实现自己的类型处理器。mybatis中内建的cd处理?Type Handler )



六、ObjectFactory    每次创徏新的l果对象是调用这个ObjectFactory的对象来q行创徏Q它会比直接调用构造函数创建对象做更多的工?/p>


七、plugins主要用来实现拦截器的功能Q用到了动态代理,可以指定在某些操作时执行一些拦截操作,比如在一条记录插入数据库之前写入一条日志,或查询一?/p>

权限{等

?nbsp; Executor
(update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
?nbsp; ParameterHandler 
(getParameterObject, setParameters)
?nbsp; ResultSetHandler 
(handleResultSets, handleOutputParameters)
?nbsp; StatementHandler 
(prepare, parameterize, batch, update, query)


 

  1. // ExamplePlugin.java 
  2. @Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) }) 
  3. public class ExamplePlugin implements Interceptor { 
  4.     public Object intercept(Invocation invocation) throws Throwable { 
  5.         return invocation.proceed(); 
  6.     } 
  7.  
  8.     public Object plugin(Object target) { 
  9.         return Plugin.wrap(target, this); 
  10.     } 
  11.  
  12.     public void setProperties(Properties properties) { 
  13.     } 

  1. <plugins>  
  2.   <plugin interceptor="org.mybatis.example.ExamplePlugin">  
  3.     <property name="someProperty" value="100"/>  
  4.   </plugin>  
  5. </plugins>  

׃在所有执行update动作之前q行拦截Q执行ExamplePlugin中自定义的一些逻辑

 

对selectq行拦截的plugin

 

  1. import org.apache.ibatis.session.ResultHandler; 
  2. import org.apache.ibatis.session.RowBounds; 
  3.  
  4. @Intercepts({ @Signature(args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }, method = "query", type = Executor.class) }) 
  5. public class LogInterceptor implements Interceptor { 
  6.  
  7.     int index; 
  8.  
  9.     @Override 
  10.     public Object intercept(Invocation invocation) throws Throwable { 
  11.         System.out.println("some log!!!"); 
  12.         return invocation.proceed(); 
  13.     } 
  14.  
  15.     @Override 
  16.     public Object plugin(Object target) { 
  17.         System.out.println("1223--------------" + (index++)); 
  18.         return Plugin.wrap(target, this); 
  19.     } 
  20.  
  21.     @Override 
  22.     public void setProperties(Properties properties) { 
  23.  
  24.     } 

  1. <plugins> 
  2.     <plugin interceptor="com.akwolf.interceptor.LogInterceptor"> 
  3.     </plugin> 
  4.    </plugins> 


 

八、environments 对于一个应用可能连接多个数据库Q那需要配|不同的环境来连接不同的数据库,每一个SqlSessionFactory对应一个environments

也可以设|不同的环境应用于开发或试的环?/p>

如果环境被忽略,那么默认环境会被加载,也就是default="development"的作用了


九、transactionManager讄事物的管理类型是 type=”[JDBC|MANAGED]”

JDBC使用datasource的连接来理事物范围?/p>

MANAGED自己不进行事物的提交和回滚,依靠容器来管理事物,讄closeConnection为falseQ取消自动关闭连?/p>

 

  1. <transactionManager type="MANAGED">  
  2.     <property name="closeConnection" value="false"/>  
  3. </transactionManager>  

十、dataSource讄数据源[UNPOOLED|POOLED|JNDI]

 

POOLED:每次被请求时单打开和关闭连?br />

POOLED:JDBC q接对象的数据源q接池的实现Q用来避免创建新的连接实例时必要的初始连接和认证旉?br />

poolMaximumActiveConnections –  在Q意时间存在的zdQ也是正在使用Q连接的数量。默认|10

poolMaximumIdleConnections –  L旉存在的空闲连接数?/span>

oolMaximumCheckoutTime –  在被强制q回之前Q池中连接被查的旉。默认|20000 毫秒Q也是 20 U)

poolTimeToWait  –  q是l连接池一个打印日志状态机会的低层ơ设|,q有重新试获得q接Q这些情况下往往需要很长时_Z避免q接池没有配|时静默p|Q?默认|20000 毫秒Q也是 20 U)

poolPingQuery –  发送到数据的侦查询,用来验证q接是否正常工作Qƈ且准备接受请求。默认是“NO PING QUERY SET”Q这会引赯多数据库驱动q接׃个错误信 息而导致失败?

poolPingEnabled  –  q是开启或用侦测查询。如果开启,你必ȝ一个合法的SQL语句Q最好是很快速的Q设|?poolPingQuery 属性。默认|false?/span>

poolPingConnectionsNotUsedFor  –  q是用来配置 poolPingQuery 多次旉被用一ơ。这可以被设|匹配标准的数据库连接超时时_来避免不必要的侦。默认|0 Q也是所有连接每一时刻都被侦测-但仅仅当 poolPingEnabled ?true 旉用Q?nbsp;

JNDI –  q个数据源的实现是ؓ了用如 Spring 或应用服务器q类的容器,容器可以集中或在外部配置数据源,然后攄一?JNDI 上下文的引用?br />

initial_context  –  q个属性用来从初始上下文中L环境Q也是initialContext.lookupQinit ial——contextQ)。这是个可选属性,如果被忽略,那么data_source 属性将 会直接以 init ialContext 景再ơ寻找?

data_source  –  q是引用数据源实例位|的上下文的路径。它会以?init ial_context查询q回的环境ؓ背景来查找,如果 init ial_context 没有q回l果Ӟ直接以初始上?文ؓ环境来查找?



十一、mappers用来注册映射文g?/p>




alexprefect 2012-03-29 11:07 发表评论
]]>
mybatis环境搭徏Q{载)http://www.aygfsteel.com/alexprefect/articles/372966.htmlalexprefectalexprefectThu, 29 Mar 2012 03:06:00 GMThttp://www.aygfsteel.com/alexprefect/articles/372966.htmlhttp://www.aygfsteel.com/alexprefect/comments/372966.htmlhttp://www.aygfsteel.com/alexprefect/articles/372966.html#Feedback0http://www.aygfsteel.com/alexprefect/comments/commentRss/372966.htmlhttp://www.aygfsteel.com/alexprefect/services/trackbacks/372966.html最q一D|间过的有些迷茫了Q好了不能在q样了,g军_振作h开始好好学习一些东西吧。研Imybatis吧!


万里之行起于步Q从搭徏环境开始?/p>


一、下载好jar包,既然是基本环境搭建就不用弄的太复杂就加入三个最基本的jar?/p>

1、mybatis-3.1.0-SNAPSHOT.jar

2、mysql-connector-java-5.0.8-bin.jar

3、log4j-1.2.16.jar


二、mybatis是基于log4j日志框架的,恩,把log4j的日志数据配|文件也配置一下,先把别设定在debug的别上

 

  1. # Rules reminder: 
  2. # DEBUG < INFO < WARN < ERROR < FATAL 
  3.  
  4. # Global logging configuration 
  5. log4j.rootLogger=DEBUG, stdout 
  6.  
  7. # My logging configuration... 
  8. log4j.logger.org.mybatis.jpetstore=DEBUG 
  9.  
  10. ## Console output... 
  11. log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
  12. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
  13. log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n

三、现在就开始对mybatisq行配置Q配|文件ؓ一个xml文gQ文件名自己军_Q暂且就叫Configuration.xml?p> 


 

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd"> 
  4.  
  5. <configuration> 
  6.     <typeAliases> 
  7.         <!-- simple alias for full class name --> 
  8.         <typeAlias alias="User" type="com.akwolf.domain.User"/> 
  9.     </typeAliases> 
  10.     <environments default="development"> 
  11.         <environment id="development"> 
  12.             <transactionManager type="JDBC"/> 
  13.             <dataSource type="POOLED"> 
  14.                 <property name="driver" value="com.mysql.jdbc.Driver"/> 
  15.                 <property name="url" value="jdbc:mysql://192.168.2.110:3306/mybatis"/> 
  16.                 <property name="username" value="zhangh"/> 
  17.                 <property name="password" value="123456"/> 
  18.             </dataSource> 
  19.         </environment> 
  20.     </environments> 
  21.     <mappers> 
  22.         <mapper resource="com/akwolf/persistence/UserMapper.xml"/> 
  23.     </mappers> 
  24. </configuration> 

 


上面q个配置文g相当于一个全局的配|,所以在q里面配|也会媄响到其他的配|文?/p>

q里先对上面几个标签陌生标签解释一?/p>

<typeAliases>是Zؓ一个完整的cdM个别名,我猜你不会愿意在每次用到一个类旉把类的完整\劲给带上Q所以上面的User可以代表com.akwolf.domain.User

q样做的是一件很省力气的?/p>

<environments default="development">也就是在不同的环境中选择不同的配|,如果现在是开发环境连接的数据库可能就与测试连接数据库的配|不同,default代表的就是一个默认用的环境?/p><mappers>也就是注册你写了哪些Mapper映射文g?br />q个先单介l一下,下一文章就把每一个标{使用和用处罗嗦一遍?br />

四、徏立领域模型User


 

  1. import java.io.Serializable; 
  2.  
  3.  
  4. public class User implements Serializable { 
  5.     private static final long serialVersionUID = 1L; 
  6.  
  7.     private int id; 
  8.  
  9.     private String name; 
  10.     private int age; 
  11.      
  12.     //setter && getter 


 


 

五、徏立对数据库操作的dao接口

 

  1. package com.akwolf.persistence; 
  2.  
  3. import com.akwolf.domain.User; 
  4.  
  5. public interface UserMapper { 
  6.  
  7.     /**
  8.      * 通过id查询用户
  9.      *
  10.      * @param id
  11.      *            用户id
  12.      * @return 用户实体
  13.      */ 
  14.     public User getUserById(int id); 

六、编写对dao接口q行实现的Mapper【UserMapper.xml】,是一些sql语句

 

 

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 
  4. <mapper namespace="com.akwolf.persistence.UserMapper"> 
  5.     <select id="getUserById" parameterType="int" resultType="User"> 
  6.         select * from tbl_user where id = #{id} 
  7.     </select> 
  8. </mapper> 

#{id}表示传入的参敎ͼ是一个变?p> 

到此一个基本的mybatisq行环境已经搭徏hQ用试cL试一?/p>


 

  1. package com.akwolf.test; 
  2.  
  3. import java.io.IOException; 
  4. import java.io.Reader; 
  5.  
  6. import org.apache.ibatis.io.Resources; 
  7. import org.apache.ibatis.session.SqlSession; 
  8. import org.apache.ibatis.session.SqlSessionFactory; 
  9. import org.apache.ibatis.session.SqlSessionFactoryBuilder; 
  10. import org.junit.AfterClass; 
  11. import org.junit.BeforeClass; 
  12. import org.junit.Test; 
  13.  
  14. import com.akwolf.domain.User; 
  15. import com.akwolf.persistence.UserMapper; 
  16.  
  17. public class UserTest { 
  18.      
  19.     private static SqlSession session ; 
  20.      
  21.     @BeforeClass 
  22.     public static void init(){ 
  23.         // 配置文g的\?/span> 
  24.         String res = "com/akwolf/conf/Configuration.xml"
  25.         try
  26.             // 1、加载配|文?/span> 
  27.             Reader reader = Resources.getResourceAsReader(res); 
  28.             // 2、创建SqlSessionFactoryQ用于取得SqlSession 
  29.             SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader) ; 
  30.             // 3、取得一个SqlSession(对Jdbc中connection的封? 
  31.             session = factory.openSession() ; 
  32.         } catch (IOException e) { 
  33.             e.printStackTrace(); 
  34.         }  
  35.     } 
  36.  
  37.     @Test 
  38.     public void testGet() { 
  39.         // 4、取得mybatis实现q实例化好的UserMapper接口实例 
  40.         UserMapper mapper = session.getMapper(UserMapper.class) ;  
  41.         // 5、进行dao层的操作 
  42.         User u = mapper.getUserById(1) ; 
  43.         System.out.println(u); 
  44.     } 
  45.      
  46.     @AfterClass 
  47.     public static void destory(){ 
  48.         // 6、关闭SqlSession 
  49.         session.close() ; 
  50.     } 

 

上面试cȝ主要建立数据库连接ƈҎ据库q行的操作,Z方便以后查看和大家的理解Q注释写的很详细?/p>


好,到这里第一个mybatisE序q行成功Q下一ơ就研究一下Mybatis配置文g的详l配|?/p>




alexprefect 2012-03-29 11:06 发表评论
]]>
վ֩ģ壺 ƽ˳| | | | ɽ| | ˳| | Ƕ| | ľ| е| Ͽ| | ˶| ˳| | ͭ| | | | | | ˮ| | | | ʯȪ| | | | ľ| ɾ| | | ͤ| ׼| | Ʊ| | Ԫ|