Mybatis 3.2.7 简单入门Demo

对最新版本  Mybatis 3.2.7  做了一个demo,做个记录

需要的基本jar:
    mybatis-3.2.7.jar 
    mysql-connector-java-5.1.27.jar


首先配置xml文件

mybatis-config.xml
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE configuration  
  3.   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
  4.   "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  5. <configuration>  
  6.       
  7.     <!-- 读取数据连接参数 -->  
  8.     <properties resource="resources/config.properties" />  
  9.   
  10.   
  11.     <settings>  
  12.         <setting name="cacheEnabled" value="true" />  
  13.         <setting name="lazyLoadingEnabled" value="true" />  
  14.         <setting name="multipleResultSetsEnabled" value="true" />  
  15.         <setting name="useColumnLabel" value="true" />  
  16.         <setting name="useGeneratedKeys" value="false" />  
  17.         <setting name="autoMappingBehavior" value="PARTIAL" />  
  18.         <setting name="defaultExecutorType" value="SIMPLE" />  
  19.         <setting name="defaultStatementTimeout" value="25" />  
  20.         <setting name="safeRowBoundsEnabled" value="false" />  
  21.         <setting name="mapUnderscoreToCamelCase" value="false" />  
  22.         <setting name="localCacheScope" value="SESSION" />  
  23.         <setting name="jdbcTypeForNull" value="OTHER" />  
  24.         <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />  
  25.     </settings>  
  26.   
  27.   
  28.     <!-- 实体类别名设置 -->  
  29.     <typeAliases>  
  30.         <typeAlias type="model.Customer" alias="Customer" />  
  31.     </typeAliases>  
  32.   
  33.   
  34.     <!-- 数据库连接环境配置 -->  
  35.     <environments default="development">  
  36.         <environment id="development">  
  37.             <!-- JDBC – 这个配置直接简单使用了 JDBC 的提交和回滚设置。 它依赖于从数据源得 到的连接来管理事务范围。 -->  
  38.             <transactionManager type="JDBC" />  
  39.             <!-- MANAGED – 这个配置几乎没做什么。它从来不提交或回滚一个连接。 而它会让 容器来管理事务的整个生命周期(比如 Spring   
  40.                 或 JEE 应用服务器的上下文) 默认 情况下它会关闭连接。 然而一些容器并不希望这样, 因此如果你需要从连接中停止 它,将 closeConnection   
  41.                 属性设置为 false。   
  42.                 <transactionManager type="MANAGED"> <property name="closeConnection"   
  43.                 value="false" />   
  44.                 </transactionManager>   
  45.             -->  
  46.             <!-- UNPOOLED – 这个数据源的实现是每次被请求时简单打开和关闭连接。  
  47.             POOLED – 这是 JDBC 连接对象的数据源连接池的实现,用来避免创建新的连接实例 时必要的初始连接和认证时间。这是一种当前 Web 应用程序用来快速响应请求很流行的方 法。  
  48.             JNDI – 这个数据源的实现是为了使用如 Spring 或应用服务器这类的容器, 容器可以集 中或在外部配置数据源,然后放置一个 JNDI 上下文的引用。  
  49.              -->  
  50.             <dataSource type="POOLED">  
  51.                 <property name="driver" value="${driver}" />  
  52.                 <property name="url" value="${url}" />  
  53.                 <property name="username" value="${username}" />  
  54.                 <property name="password" value="${password}" />  
  55.             </dataSource>  
  56.         </environment>  
  57.     </environments>  
  58.       
  59.     <!-- 多数据库配置 通过 databaseId 匹配 -->  
  60.     <databaseIdProvider type="DB_VENDOR">  
  61.         <property name="SQL Server" value="sqlserver" />  
  62.         <property name="DB2" value="db2" />  
  63.         <property name="Oracle" value="oracle" />  
  64.         <property name="MySQL" value="mysql" />  
  65.     </databaseIdProvider>  
  66.       
  67.     <!-- mapping 文件路径配置 -->  
  68.     <mappers>  
  69.         <mapper resource="mapper/CustomerMapper.xml" />  
  70.     </mappers>  
  71. </configuration>  

CustomerMapper.xml
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper  
  3.   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  4.   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  5.   
  6.   
  7. <mapper namespace="model.Customer">  
  8.   
  9.   
  10.     <resultMap id="customerResultMap" type="model.Customer">  
  11.         <id property="id" column="id" />  
  12.         <result property="name" column="username" />  
  13.         <result property="age" column="age" />  
  14.         <result property="des" column="des" />  
  15.     </resultMap>  
  16.   
  17.   
  18.   
  19.   
  20.   
  21.   
  22.     <!-- 用来定义可重用的 SQL 代码段,可以包含在其他语句中。 -->  
  23.     <sql id="customerColumns"> name,age,des </sql>  
  24.     <select id="selectCustomerAll3" resultType="Customer">  
  25.         select  
  26.         <include refid="customerColumns" />  
  27.         from customers  
  28.     </select>  
  29.   
  30.   
  31.     <!-- useGeneratedKey ( 仅 对 insert, update 有 用 ) 这 会 告 诉 MyBatis 使 用 JDBC   
  32.         的 getGeneratedKeys 方法来取出由数据 (比如:像 MySQL 和 SQL Server 这样的数据库管理系统的自动递增字段)内部生成的主键。   
  33.         默认值:false。 <selectKey keyProperty="id" resultType="int" order="BEFORE"> select   
  34.         CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1 </selectKey> #{property,javaType=int,jdbcType=NUMERIC}   
  35.         ORDER BY ${columnName} 这里 MyBatis 不会修改或转义字符串。 -->  
  36.     <insert id="saveCustomer" parameterType="model.Customer"  
  37.         useGeneratedKeys="true" keyProperty="id" flushCache="true">  
  38.         insert into  
  39.         customers(name,age,des) values (#{name}, #{age}, #{des})  
  40.     </insert>  
  41.   
  42.   
  43.     <select id="selectCustomerAll" resultType="Customer" flushCache="false" useCache="true">  
  44.         select id,name,age,des  
  45.         from customers  
  46.     </select>  
  47.       
  48.     <!--     
  49.         数组 :  
  50.         <foreach item="item" index="index" collection="array" open="(" separator="," close=")">    
  51.             #{item}    
  52.         </foreach>   
  53.     -->  
  54.     <select id="selectCustomer3" resultType="Customer">  
  55.         SELECT id,name,age,des  
  56.         FROM customers  
  57.         WHERE id in  
  58.         <foreach item="item" index="index" collection="list" open="(" separator="," close=")">  
  59.             #{id}  
  60.         </foreach>  
  61.     </select>  
  62.   
  63.   
  64.     <select id="selectCustomerByBind" parameterType="Customer" resultType="Customer">  
  65.         <!-- <bind name="pattern" value="'%' + ${name} + '%'" />  此未测试成功 -->  
  66.         <bind name="pattern" value="'%' + _parameter.getName() + '%'" />  
  67.         SELECT id,name,age,des  
  68.         FROM customers  
  69.         WHERE name like #{pattern}  
  70.     </select>  
  71.   
  72.   
  73.     <!-- resultType="hashmap" 返回一个 HashMap 类型的对象,其中的键是列名,值是列对应的值。 -->  
  74.     <select id="selectCustomerAll2" resultType="hashmap">  
  75.         select  
  76.         id,name,age,des  
  77.         from customers  
  78.     </select>  
  79.   
  80.   
  81.     <!-- 可用的收回策略有:   
  82.             LRU – 最近最少使用的:移除最长时间不被使用的对象。   
  83.             FIFO – 先进先出:按对象进入缓存的顺序来移除它们。   
  84.             SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。   
  85.             WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。   
  86.             默认的是 LRU。  
  87.         flushInterval(刷新间隔)可以被设置为任意的正整数,而且它们代表一个合理的毫秒 形式的时间段。默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新。  
  88.         size(引用数目)可以被设置为任意正整数,要记住你缓存的对象数目和你运行环境的 可用内存资源数目。默认值是 1024。  
  89.         readOnly(只读)属性可以被设置为 true 或 false。只读的缓存会给所有调用者返回缓 存对象的相同实例。因此这些对象不能被修改。  
  90.             这提供了很重要的性能优势。可读写的缓存 会返回缓存对象的拷贝(通过序列化) 。这会慢一些,但是安全,因此默认是 false。  
  91.     -->  
  92.       
  93.     <!-- <cache type="com.domain.something.MyCustomCache"/> 自定义缓存 -->  
  94.     <!-- <cache-ref namespace="com.someone.application.data.SomeMapper"/> 共享相同的缓存-->  
  95.       
  96.     <!-- 创建了一个 FIFO 缓存,并每隔 60 秒刷新,存数结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此在不同线程中的调用者之间修改它们会 导致冲突。 -->  
  97.     <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true" />  
  98.   
  99.   
  100.   
  101.   
  102. </mapper>  

Customer.java
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package model;  
  2.   
  3.   
  4. public class Customer {  
  5.       
  6.     public int id;  
  7.     public String name;  
  8.     public int age;  
  9.     public String des;  
  10.   
  11.   
  12.     public Customer() {  
  13.     }  
  14.   
  15.   
  16.     public Customer(int id, String name, int age, String des) {  
  17.         this.id = id;  
  18.         this.name = name;  
  19.         this.age = age;  
  20.         this.des = des;  
  21.     }  
  22.       
  23.     public Customer(String name, int age, String des) {  
  24.         this.name = name;  
  25.         this.age = age;  
  26.         this.des = des;  
  27.     }  
  28.       
  29.     public int getId() {  
  30.         return id;  
  31.     }  
  32.     public void setId(int id) {  
  33.         this.id = id;  
  34.     }  
  35.     public String getName() {  
  36.         return name;  
  37.     }  
  38.     public void setName(String name) {  
  39.         this.name = name;  
  40.     }  
  41.   
  42.   
  43.     public int getAge() {  
  44.         return age;  
  45.     }  
  46.   
  47.   
  48.     public void setAge(int age) {  
  49.         this.age = age;  
  50.     }  
  51.   
  52.   
  53.     public String getDes() {  
  54.         return des;  
  55.     }  
  56.     public void setDes(String des) {  
  57.         this.des = des;  
  58.     }  
  59.     @Override  
  60.     public String toString() {  
  61.         return "Customer [id=" + id + ", name=" + name + ", age=" + age  
  62.                 + ", des=" + des + "]";  
  63.     }  
  64.       
  65. }  

SessionFactoryUtil.java
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package dao;  
  2.   
  3.   
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6.   
  7.   
  8. import org.apache.ibatis.io.Resources;  
  9. import org.apache.ibatis.session.SqlSession;  
  10. import org.apache.ibatis.session.SqlSessionFactory;  
  11. import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
  12.   
  13.   
  14. public class SessionFactoryUtil {  
  15.       
  16.     private static final String MYBATIS_CONFIG_PATH = "resources/mybatis-config.xml";  
  17.       
  18.     private static InputStream is = null;  
  19.       
  20.     private static SqlSessionFactory sqlSessionFactory = null;  
  21.       
  22.     static {  
  23.         try {  
  24.             is = Resources.getResourceAsStream(MYBATIS_CONFIG_PATH);  
  25.             //SqlSessionFactoryBuilder这个类可以被实例化,使用和丢弃。一旦创建了 SqlSessionFactory 后,这个类就不需 要存在了。   
  26.             //因此 SqlSessionFactoryBuilder 实例的最佳范围是方法范围 (也就是本地方法变量)。  
  27.             sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);   
  28.         } catch (IOException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.           
  32.     }  
  33.     /** 
  34.      * 私有构造器 
  35.      */  
  36.     private SessionFactoryUtil(){};  
  37.       
  38.     /** 
  39.      *  SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次 
  40.      *  最简单的就是使用单例模式或者静态单例模式。 
  41.      * @return SqlSessionFactory 
  42.      */  
  43.     public static SqlSessionFactory getSqlSessionFactoryIntance(){  
  44.           
  45.         return sqlSessionFactory;  
  46.           
  47.     }  
  48.       
  49.     /** 
  50.      * 每个线程都应该有它自己的 SqlSession 实例。 
  51.      * SqlSession 的实例不能被共享,也是线程 不安全的。 
  52.      * 因此最佳的范围是请求或方法范围。 
  53.      * 绝对不能将 SqlSession 实例的引用放在一个 类的静态字段甚至是实例字段中。 
  54.      * @return SqlSession 
  55.      */  
  56.     public static SqlSession getSqlSessionIntance() {  
  57.   
  58.   
  59.         return sqlSessionFactory.openSession();  
  60.           
  61.     }  
  62.       
  63. }  

测试:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package dao;  
  2.   
  3.   
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8.   
  9. import model.Customer;  
  10.   
  11.   
  12. import org.apache.ibatis.session.SqlSession;  
  13. import org.junit.Test;  
  14.   
  15.   
  16. public class CustomerDao {  
  17.   
  18.   
  19.     public CustomerDao() {  
  20.     }  
  21.   
  22.   
  23.     @Test  
  24.     public void findCustomer() {  
  25.   
  26.   
  27.         //SqlSessionFactory ssf = null;  
  28.         SqlSession sqlSession = null;  
  29.         try {  
  30.             //ssf = SessionFactoryUtil.getSqlSessionFactoryIntance();  
  31.             sqlSession = SessionFactoryUtil.getSqlSessionIntance();  
  32.             System.out.println(sqlSession); //每次都是新建一个SqlSession实例org.apache.ibatis.session.defaults.DefaultSqlSession@dc57db  
  33.               
  34.             //sqlSession = SessionFactoryUtil.getSqlSessionIntance();  
  35.             //System.out.println(sqlSession); //每次都是新建一个SqlSession实例org.apache.ibatis.session.defaults.DefaultSqlSession@c24c0  
  36.               
  37.             //resultType="hashmap"  返回类型为 Map<id,Map<列名,值>>  
  38.             Map<Object, Object> customerMap = (Map<Object, Object>) sqlSession.selectMap("selectCustomerAll2""id");  
  39.             System.out.println("customerMap : " + customerMap);  
  40.             for(Map.Entry<Object, Object> customerSingle : customerMap.entrySet()) {  
  41.                 System.out.println("customerMap : " + customerSingle);  
  42.                 System.out.println("customerMap_Key : " + customerSingle.getKey());  
  43.                 System.out.println("customerMap_Value : " + customerSingle.getValue());  
  44.                 @SuppressWarnings("unchecked")  
  45.                 Map<Object, Object> map = (Map<Object, Object>) customerSingle.getValue();  
  46.                 System.out.println("Name : " + map.get("name"));  
  47.             }  
  48.               
  49.             //resultType="Customer" 自动封装成 list  
  50.             //如果没有查到数据,返回长度为0的list  
  51.             //List<Customer> customerList = sqlSession.selectList("selectCustomerAll");  
  52.               
  53.             //测试 bind 用于  like 查询  
  54.             Customer customerBind = new Customer("Man",110,"service");  
  55.             List<Customer> customerList = sqlSession.selectList("selectCustomerByBind", customerBind);  
  56.   
  57.             System.out.println("customerList : " + customerList);  
  58.             System.out.println("customerList : " + customerList.size());  
  59.               
  60.             List<Customer> customerList1 = new ArrayList<Customer>();  
  61.             System.out.println("customerList1 : " + customerList1);  
  62.             System.out.println("customerList1 : " + customerList1.size());  
  63.               
  64.             for (Customer customer : customerList) {  
  65.                 System.out.println(customer);  
  66.             }  
  67.               
  68.         } catch (Exception e) {  
  69.             e.printStackTrace();  
  70.         } finally {  
  71.             if(sqlSession != null) {  
  72.                 sqlSession.close();  
  73.             }  
  74.         }  
  75.   
  76.   
  77.     }  
  78.   
  79.   
  80.     @Test  
  81.     public void saveCustomer() {  
  82.           
  83.         SqlSession sqlSession = null;  
  84.         try {  
  85.             sqlSession = SessionFactoryUtil.getSqlSessionIntance();  
  86.               
  87.             Customer customer = new Customer("herry",110,"service");  
  88.             int id = sqlSession.insert("saveCustomer", customer); //返回影响的行数  
  89.             System.out.println(id);  
  90.             System.out.println(customer.getId()); //id 已经被set为 自增长的 key  
  91.               
  92.             sqlSession.commit();  
  93.         } catch (Exception e) {  
  94.             e.printStackTrace();  
  95.             sqlSession.rollback();  
  96.         }finally {  
  97.             sqlSession.close();  
  98.         }  
  99.     } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值