MyBatis入门

本文介绍了MyBatis持久层框架的基本概念与配置方法,并通过一个CRUD操作案例详细展示了如何利用MyBatis进行数据库交互,包括SqlSessionFactory的创建、Mapper接口的使用以及常见生命周期管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引用:http://xdwangiflytek.iteye.com/blog/1745560

在前面简单学习了iBatis ,因为项目中使用了MyBatis,所以给了一个机会能够实战中总结总结MyBatis。

首先我门简单了解一下什么是MyBatis。 MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架,MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJOs映射成数据库中的记录。

    从事Java开发在接触常用的J2EE框架时,都应该知道这些框架都需要提供一个全局配置文件,用于指定程序正常运行所需要的设置和参数信息。而针对常用的持久层框架而言(Hibernate、JPA、MyBatis|iBatis等),则通常需要配置两类文件:一类用于指定数据源、事务属性以及其他一些参数配置信息(通常是一个独立的文件,全局配置文件);另一类则用于指定数据库表与程序实体之间的映射信息(可能不止一个哦,映射文件)。

首先我们以一个CURD的操作来进行说明

每一个MyBatis的应用程序都是以一个SqlSessionFactory对象的实例为核心,SqlSessionFactory 对象 的 实 例 可 以 通 过 SqlSessionFactoryBuilder 对 象 来 获 得 。 SqlSessionFactoryBuilder 对象可以从 XML 配置文件,或从 Configuration 类的习惯准备的实例中构建 SqlSessionFactory 对象(通过Java类的方式大家可以查阅一下官方的文档)。这里我们建议使用XML的形式。

这里我们可以写一个工具类,专门是为了获取SqlSessionFactory对象,MyBatisUtil.java

Java代码   收藏代码
  1. package com.iflytek.util;  
  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.SqlSessionFactory;  
  8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
  9.   
  10. /** 
  11.  * @author xdwang 
  12.  *  
  13.  * @ceate 2012-12-10 下午6:30:53 
  14.  *  
  15.  * @description MyBatis帮助类,获取SqlSessionFactory 
  16.  *  
  17.  */  
  18. public class MyBatisUtil {  
  19.   
  20.     private static SqlSessionFactory factory;  
  21.   
  22.     private MyBatisUtil() {  
  23.     }  
  24.   
  25.     static {  
  26.         Reader reader = null;  
  27.         try {  
  28.             reader = Resources.getResourceAsReader("com/iflytek/resources/mybatis-config.xml");  
  29.             // InputStream inputStream =  
  30.             // Resources.getResourceAsStream("com/iflytek/resources/mybatis-config.xml");  
  31.             // factory = new SqlSessionFactoryBuilder().build(inputStream);  
  32.         } catch (IOException e) {  
  33.             throw new RuntimeException(e.getMessage());  
  34.         }  
  35.         factory = new SqlSessionFactoryBuilder().build(reader);  
  36.     }  
  37.   
  38.     /** 
  39.      * @descrption 获取SqlSessionFactory对象 
  40.      * @author xdwang 
  41.      * @create 2012-12-10下午6:32:24 
  42.      * @return 返回SqlSessionFactory对象 
  43.      */  
  44.     public static SqlSessionFactory getSqlSessionFactory() {  
  45.         return factory;  
  46.     }  
  47. }  

 上面指定的资源
mybatis-config.xml

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  3.   
  4. <!-- version: $Id$ -->  
  5. <configuration>  
  6.     <!-- 引用JDBC属性的配置文件 -->  
  7.     <properties resource="database.properties" />  
  8.   
  9.     <settings>  
  10.         <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->  
  11.         <setting name="useGeneratedKeys" value="true" />  
  12.         <setting name="defaultExecutorType" value="REUSE" />  
  13.     </settings>  
  14.   
  15.     <environments default="development">  
  16.         <environment id="development">  
  17.             <!-- 使用JDBC的事务管理 -->  
  18.             <transactionManager type="JDBC" />  
  19.             <!-- POOLED :JDBC连接对象的数据源连接池的实现,不直接支持第三方数据库连接池 -->  
  20.             <dataSource type="POOLED">  
  21.                 <property name="driver" value="${database.driver}" />  
  22.                 <property name="url" value="${database.url}" />  
  23.                 <property name="username" value="${database.username}" />  
  24.                 <property name="password" value="${database.password}" />  
  25.             </dataSource>  
  26.         </environment>  
  27.   
  28.     </environments>  
  29.   
  30.     <!-- ORM映射文件 -->  
  31.     <mappers>  
  32.         <!-- 注解的方式 -->  
  33.         <mapper class="com.iflytek.dao.mapper.BlogMapper" />  
  34.         <!-- XML的方式 -->  
  35.         <mapper resource="com/iflytek/dao/xml/StudentMapper.xml" />  
  36.         <!-- 这里对于注解,还可以通过<package name="com.iflytek.dao.mapper"/> -->  
  37.     </mappers>  
  38. </configuration>  
 

这里先简单列举重要的节点,后面再详细描述
database.properties

Java代码   收藏代码
  1. database.driver=com.mysql.jdbc.Driver  
  2. database.url=jdbc:mysql://localhost:3306/ibatis  
  3. database.username=root  
  4. database.password=123  
 

下面我们有了SqlSessionFactory对象,可以通过SqlSessionFactory构造SqlSession,再通过SqlSession获取不同实体对应的Mapper接口,最后通过Mapper接口中定义的方法进行相关的数据操作。
对于Mapper接口的定义,有两种方式,一是通过XML的方式,二是通过注解的方式。
一、XML方式(这里的Model、Mapper、XML是通过generator自动生成的)
Student.java

Java代码   收藏代码
  1. package com.iflytek.dao.model;  
  2.   
  3. import java.text.MessageFormat;  
  4. import java.util.Date;  
  5.   
  6. public class Student {  
  7.     private Integer id;  
  8.   
  9.     private String name;  
  10.   
  11.     private Date birth;  
  12.   
  13.     private Float score;  
  14.   
  15.     public Integer getId() {  
  16.         return id;  
  17.     }  
  18.   
  19.     public void setId(Integer id) {  
  20.         this.id = id;  
  21.     }  
  22.   
  23.     public String getName() {  
  24.         return name;  
  25.     }  
  26.   
  27.     public void setName(String name) {  
  28.         this.name = name == null ? null : name.trim();  
  29.     }  
  30.   
  31.     public Date getBirth() {  
  32.         return birth;  
  33.     }  
  34.   
  35.     public void setBirth(Date birth) {  
  36.         this.birth = birth;  
  37.     }  
  38.   
  39.     public Float getScore() {  
  40.         return score;  
  41.     }  
  42.   
  43.     public void setScore(Float score) {  
  44.         this.score = score;  
  45.     }  
  46.   
  47.     @Override  
  48.     public String toString() {  
  49.         return MessageFormat.format("id:{0},姓名:{1},出生日期:{2},分数:{3}", id, name, birth, score);  
  50.     }  
  51. }  

 StudentExample.java

Java代码   收藏代码
  1. package com.iflytek.dao.model;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Date;  
  5. import java.util.Iterator;  
  6. import java.util.List;  
  7.   
  8. public class StudentExample {  
  9.     protected String orderByClause;  
  10.   
  11.     protected boolean distinct;  
  12.   
  13.     protected List<Criteria> oredCriteria;  
  14.   
  15.     public StudentExample() {  
  16.         oredCriteria = new ArrayList<Criteria>();  
  17.     }  
  18.   
  19.     public void setOrderByClause(String orderByClause) {  
  20.         this.orderByClause = orderByClause;  
  21.     }  
  22.   
  23.     public String getOrderByClause() {  
  24.         return orderByClause;  
  25.     }  
  26.   
  27.     public void setDistinct(boolean distinct) {  
  28.         this.distinct = distinct;  
  29.     }  
  30.   
  31.     public boolean isDistinct() {  
  32.         return distinct;  
  33.     }  
  34.   
  35.     public List<Criteria> getOredCriteria() {  
  36.         return oredCriteria;  
  37.     }  
  38.   
  39.     public void or(Criteria criteria) {  
  40.         oredCriteria.add(criteria);  
  41.     }  
  42.   
  43.     public Criteria or() {  
  44.         Criteria criteria = createCriteriaInternal();  
  45.         oredCriteria.add(criteria);  
  46.         return criteria;  
  47.     }  
  48.   
  49.     public Criteria createCriteria() {  
  50.         Criteria criteria = createCriteriaInternal();  
  51.         if (oredCriteria.size() == 0) {  
  52.             oredCriteria.add(criteria);  
  53.         }  
  54.         return criteria;  
  55.     }  
  56.   
  57.     protected Criteria createCriteriaInternal() {  
  58.         Criteria criteria = new Criteria();  
  59.         return criteria;  
  60.     }  
  61.   
  62.     public void clear() {  
  63.         oredCriteria.clear();  
  64.         orderByClause = null;  
  65.         distinct = false;  
  66.     }  
  67.   
  68.     protected abstract static class GeneratedCriteria {  
  69.         protected List<Criterion> criteria;  
  70.   
  71.         protected GeneratedCriteria() {  
  72.             super();  
  73.             criteria = new ArrayList<Criterion>();  
  74.         }  
  75.   
  76.         public boolean isValid() {  
  77.             return criteria.size() > 0;  
  78.         }  
  79.   
  80.         public List<Criterion> getAllCriteria() {  
  81.             return criteria;  
  82.         }  
  83.   
  84.         public List<Criterion> getCriteria() {  
  85.             return criteria;  
  86.         }  
  87.   
  88.         protected void addCriterion(String condition) {  
  89.             if (condition == null) {  
  90.                 throw new RuntimeException("Value for condition cannot be null");  
  91.             }  
  92.             criteria.add(new Criterion(condition));  
  93.         }  
  94.   
  95.         protected void addCriterion(String condition, Object value, String property) {  
  96.             if (value == null) {  
  97.                 throw new RuntimeException("Value for " + property + " cannot be null");  
  98.             }  
  99.             criteria.add(new Criterion(condition, value));  
  100.         }  
  101.   
  102.         protected void addCriterion(String condition, Object value1, Object value2, String property) {  
  103.             if (value1 == null || value2 == null) {  
  104.                 throw new RuntimeException("Between values for " + property + " cannot be null");  
  105.             }  
  106.             criteria.add(new Criterion(condition, value1, value2));  
  107.         }  
  108.   
  109.         protected void addCriterionForJDBCDate(String condition, Date value, String property) {  
  110.             if (value == null) {  
  111.                 throw new RuntimeException("Value for " + property + " cannot be null");  
  112.             }  
  113.             addCriterion(condition, new java.sql.Date(value.getTime()), property);  
  114.         }  
  115.   
  116.         protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) {  
  117.             if (values == null || values.size() == 0) {  
  118.                 throw new RuntimeException("Value list for " + property + " cannot be null or empty");  
  119.             }  
  120.             List<java.sql.Date> dateList = new ArrayList<java.sql.Date>();  
  121.             Iterator<Date> iter = values.iterator();  
  122.             while (iter.hasNext()) {  
  123.                 dateList.add(new java.sql.Date(iter.next().getTime()));  
  124.             }  
  125.             addCriterion(condition, dateList, property);  
  126.         }  
  127.   
  128.         protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {  
  129.             if (value1 == null || value2 == null) {  
  130.                 throw new RuntimeException("Between values for " + property + " cannot be null");  
  131.             }  
  132.             addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);  
  133.         }  
  134.   
  135.         public Criteria andIdIsNull() {  
  136.             addCriterion("id is null");  
  137.             return (Criteria) this;  
  138.         }  
  139.   
  140.         public Criteria andIdIsNotNull() {  
  141.             addCriterion("id is not null");  
  142.             return (Criteria) this;  
  143.         }  
  144.   
  145.         public Criteria andIdEqualTo(Integer value) {  
  146.             addCriterion("id =", value, "id");  
  147.             return (Criteria) this;  
  148.         }  
  149.   
  150.         public Criteria andIdNotEqualTo(Integer value) {  
  151.             addCriterion("id <>", value, "id");  
  152.             return (Criteria) this;  
  153.         }  
  154.   
  155.         public Criteria andIdGreaterThan(Integer value) {  
  156.             addCriterion("id >", value, "id");  
  157.             return (Criteria) this;  
  158.         }  
  159.   
  160.         public Criteria andIdGreaterThanOrEqualTo(Integer value) {  
  161.             addCriterion("id >=", value, "id");  
  162.             return (Criteria) this;  
  163.         }  
  164.   
  165.         public Criteria andIdLessThan(Integer value) {  
  166.             addCriterion("id <", value, "id");  
  167.             return (Criteria) this;  
  168.         }  
  169.   
  170.         public Criteria andIdLessThanOrEqualTo(Integer value) {  
  171.             addCriterion("id <=", value, "id");  
  172.             return (Criteria) this;  
  173.         }  
  174.   
  175.         public Criteria andIdIn(List<Integer> values) {  
  176.             addCriterion("id in", values, "id");  
  177.             return (Criteria) this;  
  178.         }  
  179.   
  180.         public Criteria andIdNotIn(List<Integer> values) {  
  181.             addCriterion("id not in", values, "id");  
  182.             return (Criteria) this;  
  183.         }  
  184.   
  185.         public Criteria andIdBetween(Integer value1, Integer value2) {  
  186.             addCriterion("id between", value1, value2, "id");  
  187.             return (Criteria) this;  
  188.         }  
  189.   
  190.         public Criteria andIdNotBetween(Integer value1, Integer value2) {  
  191.             addCriterion("id not between", value1, value2, "id");  
  192.             return (Criteria) this;  
  193.         }  
  194.   
  195.         public Criteria andNameIsNull() {  
  196.             addCriterion("name is null");  
  197.             return (Criteria) this;  
  198.         }  
  199.   
  200.         public Criteria andNameIsNotNull() {  
  201.             addCriterion("name is not null");  
  202.             return (Criteria) this;  
  203.         }  
  204.   
  205.         public Criteria andNameEqualTo(String value) {  
  206.             addCriterion("name =", value, "name");  
  207.             return (Criteria) this;  
  208.         }  
  209.   
  210.         public Criteria andNameNotEqualTo(String value) {  
  211.             addCriterion("name <>", value, "name");  
  212.             return (Criteria) this;  
  213.         }  
  214.   
  215.         public Criteria andNameGreaterThan(String value) {  
  216.             addCriterion("name >", value, "name");  
  217.             return (Criteria) this;  
  218.         }  
  219.   
  220.         public Criteria andNameGreaterThanOrEqualTo(String value) {  
  221.             addCriterion("name >=", value, "name");  
  222.             return (Criteria) this;  
  223.         }  
  224.   
  225.         public Criteria andNameLessThan(String value) {  
  226.             addCriterion("name <", value, "name");  
  227.             return (Criteria) this;  
  228.         }  
  229.   
  230.         public Criteria andNameLessThanOrEqualTo(String value) {  
  231.             addCriterion("name <=", value, "name");  
  232.             return (Criteria) this;  
  233.         }  
  234.   
  235.         public Criteria andNameLike(String value) {  
  236.             addCriterion("name like", value, "name");  
  237.             return (Criteria) this;  
  238.         }  
  239.   
  240.         public Criteria andNameNotLike(String value) {  
  241.             addCriterion("name not like", value, "name");  
  242.             return (Criteria) this;  
  243.         }  
  244.   
  245.         public Criteria andNameIn(List<String> values) {  
  246.             addCriterion("name in", values, "name");  
  247.             return (Criteria) this;  
  248.         }  
  249.   
  250.         public Criteria andNameNotIn(List<String> values) {  
  251.             addCriterion("name not in", values, "name");  
  252.             return (Criteria) this;  
  253.         }  
  254.   
  255.         public Criteria andNameBetween(String value1, String value2) {  
  256.             addCriterion("name between", value1, value2, "name");  
  257.             return (Criteria) this;  
  258.         }  
  259.   
  260.         public Criteria andNameNotBetween(String value1, String value2) {  
  261.             addCriterion("name not between", value1, value2, "name");  
  262.             return (Criteria) this;  
  263.         }  
  264.   
  265.         public Criteria andBirthIsNull() {  
  266.             addCriterion("birth is null");  
  267.             return (Criteria) this;  
  268.         }  
  269.   
  270.         public Criteria andBirthIsNotNull() {  
  271.             addCriterion("birth is not null");  
  272.             return (Criteria) this;  
  273.         }  
  274.   
  275.         public Criteria andBirthEqualTo(Date value) {  
  276.             addCriterionForJDBCDate("birth =", value, "birth");  
  277.             return (Criteria) this;  
  278.         }  
  279.   
  280.         public Criteria andBirthNotEqualTo(Date value) {  
  281.             addCriterionForJDBCDate("birth <>", value, "birth");  
  282.             return (Criteria) this;  
  283.         }  
  284.   
  285.         public Criteria andBirthGreaterThan(Date value) {  
  286.             addCriterionForJDBCDate("birth >", value, "birth");  
  287.             return (Criteria) this;  
  288.         }  
  289.   
  290.         public Criteria andBirthGreaterThanOrEqualTo(Date value) {  
  291.             addCriterionForJDBCDate("birth >=", value, "birth");  
  292.             return (Criteria) this;  
  293.         }  
  294.   
  295.         public Criteria andBirthLessThan(Date value) {  
  296.             addCriterionForJDBCDate("birth <", value, "birth");  
  297.             return (Criteria) this;  
  298.         }  
  299.   
  300.         public Criteria andBirthLessThanOrEqualTo(Date value) {  
  301.             addCriterionForJDBCDate("birth <=", value, "birth");  
  302.             return (Criteria) this;  
  303.         }  
  304.   
  305.         public Criteria andBirthIn(List<Date> values) {  
  306.             addCriterionForJDBCDate("birth in", values, "birth");  
  307.             return (Criteria) this;  
  308.         }  
  309.   
  310.         public Criteria andBirthNotIn(List<Date> values) {  
  311.             addCriterionForJDBCDate("birth not in", values, "birth");  
  312.             return (Criteria) this;  
  313.         }  
  314.   
  315.         public Criteria andBirthBetween(Date value1, Date value2) {  
  316.             addCriterionForJDBCDate("birth between", value1, value2, "birth");  
  317.             return (Criteria) this;  
  318.         }  
  319.   
  320.         public Criteria andBirthNotBetween(Date value1, Date value2) {  
  321.             addCriterionForJDBCDate("birth not between", value1, value2, "birth");  
  322.             return (Criteria) this;  
  323.         }  
  324.   
  325.         public Criteria andScoreIsNull() {  
  326.             addCriterion("score is null");  
  327.             return (Criteria) this;  
  328.         }  
  329.   
  330.         public Criteria andScoreIsNotNull() {  
  331.             addCriterion("score is not null");  
  332.             return (Criteria) this;  
  333.         }  
  334.   
  335.         public Criteria andScoreEqualTo(Float value) {  
  336.             addCriterion("score =", value, "score");  
  337.             return (Criteria) this;  
  338.         }  
  339.   
  340.         public Criteria andScoreNotEqualTo(Float value) {  
  341.             addCriterion("score <>", value, "score");  
  342.             return (Criteria) this;  
  343.         }  
  344.   
  345.         public Criteria andScoreGreaterThan(Float value) {  
  346.             addCriterion("score >", value, "score");  
  347.             return (Criteria) this;  
  348.         }  
  349.   
  350.         public Criteria andScoreGreaterThanOrEqualTo(Float value) {  
  351.             addCriterion("score >=", value, "score");  
  352.             return (Criteria) this;  
  353.         }  
  354.   
  355.         public Criteria andScoreLessThan(Float value) {  
  356.             addCriterion("score <", value, "score");  
  357.             return (Criteria) this;  
  358.         }  
  359.   
  360.         public Criteria andScoreLessThanOrEqualTo(Float value) {  
  361.             addCriterion("score <=", value, "score");  
  362.             return (Criteria) this;  
  363.         }  
  364.   
  365.         public Criteria andScoreIn(List<Float> values) {  
  366.             addCriterion("score in", values, "score");  
  367.             return (Criteria) this;  
  368.         }  
  369.   
  370.         public Criteria andScoreNotIn(List<Float> values) {  
  371.             addCriterion("score not in", values, "score");  
  372.             return (Criteria) this;  
  373.         }  
  374.   
  375.         public Criteria andScoreBetween(Float value1, Float value2) {  
  376.             addCriterion("score between", value1, value2, "score");  
  377.             return (Criteria) this;  
  378.         }  
  379.   
  380.         public Criteria andScoreNotBetween(Float value1, Float value2) {  
  381.             addCriterion("score not between", value1, value2, "score");  
  382.             return (Criteria) this;  
  383.         }  
  384.     }  
  385.   
  386.     public static class Criteria extends GeneratedCriteria {  
  387.   
  388.         protected Criteria() {  
  389.             super();  
  390.         }  
  391.     }  
  392.   
  393.     public static class Criterion {  
  394.         private String condition;  
  395.   
  396.         private Object value;  
  397.   
  398.         private Object secondValue;  
  399.   
  400.         private boolean noValue;  
  401.   
  402.         private boolean singleValue;  
  403.   
  404.         private boolean betweenValue;  
  405.   
  406.         private boolean listValue;  
  407.   
  408.         private String typeHandler;  
  409.   
  410.         public String getCondition() {  
  411.             return condition;  
  412.         }  
  413.   
  414.         public Object getValue() {  
  415.             return value;  
  416.         }  
  417.   
  418.         public Object getSecondValue() {  
  419.             return secondValue;  
  420.         }  
  421.   
  422.         public boolean isNoValue() {  
  423.             return noValue;  
  424.         }  
  425.   
  426.         public boolean isSingleValue() {  
  427.             return singleValue;  
  428.         }  
  429.   
  430.         public boolean isBetweenValue() {  
  431.             return betweenValue;  
  432.         }  
  433.   
  434.         public boolean isListValue() {  
  435.             return listValue;  
  436.         }  
  437.   
  438.         public String getTypeHandler() {  
  439.             return typeHandler;  
  440.         }  
  441.   
  442.         protected Criterion(String condition) {  
  443.             super();  
  444.             this.condition = condition;  
  445.             this.typeHandler = null;  
  446.             this.noValue = true;  
  447.         }  
  448.   
  449.         protected Criterion(String condition, Object value, String typeHandler) {  
  450.             super();  
  451.             this.condition = condition;  
  452.             this.value = value;  
  453.             this.typeHandler = typeHandler;  
  454.             if (value instanceof List<?>) {  
  455.                 this.listValue = true;  
  456.             } else {  
  457.                 this.singleValue = true;  
  458.             }  
  459.         }  
  460.   
  461.         protected Criterion(String condition, Object value) {  
  462.             this(condition, value, null);  
  463.         }  
  464.   
  465.         protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {  
  466.             super();  
  467.             this.condition = condition;  
  468.             this.value = value;  
  469.             this.secondValue = secondValue;  
  470.             this.typeHandler = typeHandler;  
  471.             this.betweenValue = true;  
  472.         }  
  473.   
  474.         protected Criterion(String condition, Object value, Object secondValue) {  
  475.             this(condition, value, secondValue, null);  
  476.         }  
  477.     }  
  478. }  

 StudentMapper.xml

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  
  3. <mapper namespace="com.iflytek.dao.mapper.StudentMapper" >  
  4.   <resultMap id="BaseResultMap" type="com.iflytek.dao.model.Student" >  
  5.     <id column="id" property="id" jdbcType="INTEGER" />  
  6.     <result column="name" property="name" jdbcType="VARCHAR" />  
  7.     <result column="birth" property="birth" jdbcType="DATE" />  
  8.     <result column="score" property="score" jdbcType="REAL" />  
  9.   </resultMap>  
  10.   <sql id="Example_Where_Clause" >  
  11.     <where >  
  12.       <foreach collection="oredCriteria" item="criteria" separator="or" >  
  13.         <if test="criteria.valid" >  
  14.           <trim prefix="(" suffix=")" prefixOverrides="and" >  
  15.             <foreach collection="criteria.criteria" item="criterion" >  
  16.               <choose >  
  17.                 <when test="criterion.noValue" >  
  18.                   and ${criterion.condition}  
  19.                 </when>  
  20.                 <when test="criterion.singleValue" >  
  21.                   and ${criterion.condition} #{criterion.value}  
  22.                 </when>  
  23.                 <when test="criterion.betweenValue" >  
  24.                   and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}  
  25.                 </when>  
  26.                 <when test="criterion.listValue" >  
  27.                   and ${criterion.condition}  
  28.                   <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >  
  29.                     #{listItem}  
  30.                   </foreach>  
  31.                 </when>  
  32.               </choose>  
  33.             </foreach>  
  34.           </trim>  
  35.         </if>  
  36.       </foreach>  
  37.     </where>  
  38.   </sql>  
  39.   <sql id="Update_By_Example_Where_Clause" >  
  40.     <where >  
  41.       <foreach collection="example.oredCriteria" item="criteria" separator="or" >  
  42.         <if test="criteria.valid" >  
  43.           <trim prefix="(" suffix=")" prefixOverrides="and" >  
  44.             <foreach collection="criteria.criteria" item="criterion" >  
  45.               <choose >  
  46.                 <when test="criterion.noValue" >  
  47.                   and ${criterion.condition}  
  48.                 </when>  
  49.                 <when test="criterion.singleValue" >  
  50.                   and ${criterion.condition} #{criterion.value}  
  51.                 </when>  
  52.                 <when test="criterion.betweenValue" >  
  53.                   and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}  
  54.                 </when>  
  55.                 <when test="criterion.listValue" >  
  56.                   and ${criterion.condition}  
  57.                   <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >  
  58.                     #{listItem}  
  59.                   </foreach>  
  60.                 </when>  
  61.               </choose>  
  62.             </foreach>  
  63.           </trim>  
  64.         </if>  
  65.       </foreach>  
  66.     </where>  
  67.   </sql>  
  68.   <sql id="Base_Column_List" >  
  69.     id, name, birth, score  
  70.   </sql>  
  71.   <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.iflytek.dao.model.StudentExample" >  
  72.     select  
  73.     <if test="distinct" >  
  74.       distinct  
  75.     </if>  
  76.     <include refid="Base_Column_List" />  
  77.     from tbl_student  
  78.     <if test="_parameter != null" >  
  79.       <include refid="Example_Where_Clause" />  
  80.     </if>  
  81.     <if test="orderByClause != null" >  
  82.       order by ${orderByClause}  
  83.     </if>  
  84.   </select>  
  85.   <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >  
  86.     select   
  87.     <include refid="Base_Column_List" />  
  88.     from tbl_student  
  89.     where id = #{id,jdbcType=INTEGER}  
  90.   </select>  
  91.   <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >  
  92.     delete from tbl_student  
  93.     where id = #{id,jdbcType=INTEGER}  
  94.   </delete>  
  95.   <delete id="deleteByExample" parameterType="com.iflytek.dao.model.StudentExample" >  
  96.     delete from tbl_student  
  97.     <if test="_parameter != null" >  
  98.       <include refid="Example_Where_Clause" />  
  99.     </if>  
  100.   </delete>  
  101.   <insert id="insert" parameterType="com.iflytek.dao.model.Student" >  
  102.     <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >  
  103.       SELECT LAST_INSERT_ID()  
  104.     </selectKey>  
  105.     insert into tbl_student (name, birth, score)  
  106.     values (#{name,jdbcType=VARCHAR}, #{birth,jdbcType=DATE}, #{score,jdbcType=REAL})  
  107.   </insert>  
  108.   <insert id="insertSelective" parameterType="com.iflytek.dao.model.Student" >  
  109.     <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >  
  110.       SELECT LAST_INSERT_ID()  
  111.     </selectKey>  
  112.     insert into tbl_student  
  113.     <trim prefix="(" suffix=")" suffixOverrides="," >  
  114.       <if test="name != null" >  
  115.         name,  
  116.       </if>  
  117.       <if test="birth != null" >  
  118.         birth,  
  119.       </if>  
  120.       <if test="score != null" >  
  121.         score,  
  122.       </if>  
  123.     </trim>  
  124.     <trim prefix="values (" suffix=")" suffixOverrides="," >  
  125.       <if test="name != null" >  
  126.         #{name,jdbcType=VARCHAR},  
  127.       </if>  
  128.       <if test="birth != null" >  
  129.         #{birth,jdbcType=DATE},  
  130.       </if>  
  131.       <if test="score != null" >  
  132.         #{score,jdbcType=REAL},  
  133.       </if>  
  134.     </trim>  
  135.   </insert>  
  136.   <select id="countByExample" parameterType="com.iflytek.dao.model.StudentExample" resultType="java.lang.Integer" >  
  137.     select count(*) from tbl_student  
  138.     <if test="_parameter != null" >  
  139.       <include refid="Example_Where_Clause" />  
  140.     </if>  
  141.   </select>  
  142.   <update id="updateByExampleSelective" parameterType="map" >  
  143.     update tbl_student  
  144.     <set >  
  145.       <if test="record.id != null" >  
  146.         id = #{record.id,jdbcType=INTEGER},  
  147.       </if>  
  148.       <if test="record.name != null" >  
  149.         name = #{record.name,jdbcType=VARCHAR},  
  150.       </if>  
  151.       <if test="record.birth != null" >  
  152.         birth = #{record.birth,jdbcType=DATE},  
  153.       </if>  
  154.       <if test="record.score != null" >  
  155.         score = #{record.score,jdbcType=REAL},  
  156.       </if>  
  157.     </set>  
  158.     <if test="_parameter != null" >  
  159.       <include refid="Update_By_Example_Where_Clause" />  
  160.     </if>  
  161.   </update>  
  162.   <update id="updateByExample" parameterType="map" >  
  163.     update tbl_student  
  164.     set id = #{record.id,jdbcType=INTEGER},  
  165.       name = #{record.name,jdbcType=VARCHAR},  
  166.       birth = #{record.birth,jdbcType=DATE},  
  167.       score = #{record.score,jdbcType=REAL}  
  168.     <if test="_parameter != null" >  
  169.       <include refid="Update_By_Example_Where_Clause" />  
  170.     </if>  
  171.   </update>  
  172.   <update id="updateByPrimaryKeySelective" parameterType="com.iflytek.dao.model.Student" >  
  173.     update tbl_student  
  174.     <set >  
  175.       <if test="name != null" >  
  176.         name = #{name,jdbcType=VARCHAR},  
  177.       </if>  
  178.       <if test="birth != null" >  
  179.         birth = #{birth,jdbcType=DATE},  
  180.       </if>  
  181.       <if test="score != null" >  
  182.         score = #{score,jdbcType=REAL},  
  183.       </if>  
  184.     </set>  
  185.     where id = #{id,jdbcType=INTEGER}  
  186.   </update>  
  187.   <update id="updateByPrimaryKey" parameterType="com.iflytek.dao.model.Student" >  
  188.     update tbl_student  
  189.     set name = #{name,jdbcType=VARCHAR},  
  190.       birth = #{birth,jdbcType=DATE},  
  191.       score = #{score,jdbcType=REAL}  
  192.     where id = #{id,jdbcType=INTEGER}  
  193.   </update>  
  194. </mapper>  
 

StudentMapper.java

Java代码   收藏代码
  1. package com.iflytek.dao.mapper;  
  2.   
  3. import com.iflytek.dao.model.Student;  
  4. import com.iflytek.dao.model.StudentExample;  
  5. import java.util.List;  
  6. import org.apache.ibatis.annotations.Param;  
  7.   
  8. public interface StudentMapper {  
  9.     int countByExample(StudentExample example);  
  10.   
  11.     int deleteByExample(StudentExample example);  
  12.   
  13.     int deleteByPrimaryKey(Integer id);  
  14.   
  15.     int insert(Student record);  
  16.   
  17.     int insertSelective(Student record);  
  18.   
  19.     List<Student> selectByExample(StudentExample example);  
  20.   
  21.     Student selectByPrimaryKey(Integer id);  
  22.   
  23.     int updateByExampleSelective(@Param("record") Student record, @Param("example") StudentExample example);  
  24.   
  25.     int updateByExample(@Param("record") Student record, @Param("example") StudentExample example);  
  26.   
  27.     int updateByPrimaryKeySelective(Student record);  
  28.   
  29.     int updateByPrimaryKey(Student record);  
  30. }  
 

StudentService.java

Java代码   收藏代码
  1. package com.iflytek.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.ibatis.session.SqlSession;  
  6.   
  7. import com.iflytek.dao.mapper.StudentMapper;  
  8. import com.iflytek.dao.model.Student;  
  9. import com.iflytek.dao.model.StudentExample;  
  10. import com.iflytek.util.MyBatisUtil;  
  11.   
  12. /** 
  13.  *  
  14.  * @author xdwang 
  15.  *  
  16.  * @ceate 2012-12-10 下午6:33:26 
  17.  *  
  18.  * @description 业务逻辑层,Mapper和XML是通过generator自动生成的 
  19.  *  
  20.  */  
  21. public class StudentService {  
  22.   
  23.     /** 
  24.      * @descrption 添加 
  25.      * @author xdwang 
  26.      * @create 2012-12-10下午6:42:48 
  27.      * @param student 
  28.      *            学生实体 
  29.      * @return 是否成功 
  30.      */  
  31.     public boolean insertStudent(Student student) {  
  32.         boolean flag = false;  
  33.         SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();  
  34.         try {  
  35.             StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);  
  36.             int result = studentMapper.insert(student);  
  37.             if (result > 0) {  
  38.                 flag = true;  
  39.             }  
  40.             sqlSession.commit();  
  41.         } finally {  
  42.             sqlSession.close();  
  43.         }  
  44.         return flag;  
  45.     }  
  46.   
  47.     /** 
  48.      * @descrption 根据学生id获取学生实体信息 
  49.      * @author xdwang 
  50.      * @create 2012-12-10下午6:46:09 
  51.      * @param studentId 
  52.      *            学生id 
  53.      * @return 学生实体信息 
  54.      */  
  55.     public Student getStudentById(int studentId) {  
  56.         SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();  
  57.         try {  
  58.             StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class);  
  59.             return StudentMapper.selectByPrimaryKey(studentId);  
  60.         } finally {  
  61.             sqlSession.close();  
  62.         }  
  63.     }  
  64.   
  65.     /** 
  66.      * @descrption 获取所有学生信息集合 
  67.      * @author xdwang 
  68.      * @create 2012-12-10下午6:46:55 
  69.      * @return 学生集合 
  70.      */  
  71.     public List<Student> getAllStudents() {  
  72.         SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();  
  73.         try {  
  74.             StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class);  
  75.             return StudentMapper.selectByExample(new StudentExample());  
  76.         } finally {  
  77.             sqlSession.close();  
  78.         }  
  79.     }  
  80.   
  81.     /** 
  82.      * @descrption 更新学生信息 
  83.      * @author xdwang 
  84.      * @create 2012-12-10下午6:47:13 
  85.      * @param Student 
  86.      *            学生实体信息 
  87.      * @return 更新成功与否 
  88.      */  
  89.     public boolean updateStudent(Student Student) {  
  90.         SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();  
  91.         boolean flag = false;  
  92.         try {  
  93.             StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class);  
  94.             int result = StudentMapper.updateByPrimaryKey(Student);  
  95.             if (result > 0) {  
  96.                 flag = true;  
  97.             }  
  98.             sqlSession.commit();  
  99.         } finally {  
  100.             sqlSession.close();  
  101.         }  
  102.         return flag;  
  103.   
  104.     }  
  105.   
  106.     /** 
  107.      * @descrption 根据学生id删除学生信息 
  108.      * @author xdwang 
  109.      * @create 2012-12-10下午6:49:05 
  110.      * @param studentId 
  111.      *            学生id 
  112.      * @return 删除成功与否 
  113.      */  
  114.     public boolean deleteStudent(int studentId) {  
  115.         SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();  
  116.         boolean flag = false;  
  117.         try {  
  118.             StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class);  
  119.             int result = StudentMapper.deleteByPrimaryKey(studentId);  
  120.             if (result > 0) {  
  121.                 flag = true;  
  122.             }  
  123.             sqlSession.commit();  
  124.         } finally {  
  125.             sqlSession.close();  
  126.         }  
  127.         return flag;  
  128.     }  
  129.   
  130. }  
 

StudentServiceTest.java

Java代码   收藏代码
  1. package com.iflytek.test;  
  2.   
  3. import java.util.Date;  
  4. import java.util.List;  
  5.   
  6. import org.junit.AfterClass;  
  7. import org.junit.Assert;  
  8. import org.junit.BeforeClass;  
  9. import org.junit.Test;  
  10.   
  11. import com.iflytek.dao.model.Student;  
  12. import com.iflytek.service.StudentService;  
  13.   
  14. /** 
  15.  * @author xdwang 
  16.  *  
  17.  * @ceate 2012-12-10 下午7:02:08 
  18.  *  
  19.  * @description 测试业务逻辑 
  20.  *  
  21.  */  
  22. public class StudentServiceTest {  
  23.     private static StudentService studentService;  
  24.   
  25.     @BeforeClass  
  26.     public static void setup() {  
  27.         studentService = new StudentService();  
  28.     }  
  29.   
  30.     @AfterClass  
  31.     public static void teardown() {  
  32.         studentService = null;  
  33.     }  
  34.   
  35.     @Test  
  36.     public void testInsertStudent() {  
  37.         Student student = new Student();  
  38.         student.setName("xwang");  
  39.         student.setBirth(new Date());  
  40.         student.setScore((float) 99.5);  
  41.         System.out.println(studentService.insertStudent(student));  
  42.     }  
  43.   
  44.     @Test  
  45.     public void testGetStudentById() {  
  46.         Student student = studentService.getStudentById(1);  
  47.         Assert.assertNotNull(student);  
  48.         System.out.println(student);  
  49.     }  
  50.   
  51.     @Test  
  52.     public void testGetAllStudents() {  
  53.         List<Student> students = studentService.getAllStudents();  
  54.         Assert.assertNotNull(students);  
  55.         for (Student student : students) {  
  56.             System.out.println(student);  
  57.         }  
  58.     }  
  59.   
  60.     @Test  
  61.     public void testUpdateStudent() {  
  62.         Student student = studentService.getStudentById(1);  
  63.         student.setName("xdwang03");  
  64.         System.out.println(studentService.deleteStudent(1));  
  65.     }  
  66.   
  67.     @Test  
  68.     public void testDeleteStudent() {  
  69.         System.out.println(studentService.deleteStudent(1));  
  70.     }  
  71.   
  72. }  
 

二、注解
Blog.java

Java代码   收藏代码
  1. package com.iflytek.dao.model;  
  2.   
  3. import java.text.MessageFormat;  
  4. import java.util.Date;  
  5.   
  6. /** 
  7.  * @author xdwang 
  8.  *  
  9.  * @ceate 2012-12-10 下午7:29:08 
  10.  *  
  11.  * @description 博客实体类,手动创建 
  12.  *  
  13.  */  
  14. public class Blog {  
  15.   
  16.     private Integer blogId;  
  17.     private String blogName;  
  18.     private Date createdOn;  
  19.   
  20.     public Integer getBlogId() {  
  21.         return blogId;  
  22.     }  
  23.   
  24.     public void setBlogId(Integer blogId) {  
  25.         this.blogId = blogId;  
  26.     }  
  27.   
  28.     public String getBlogName() {  
  29.         return blogName;  
  30.     }  
  31.   
  32.     public void setBlogName(String blogName) {  
  33.         this.blogName = blogName;  
  34.     }  
  35.   
  36.     public Date getCreatedOn() {  
  37.         return createdOn;  
  38.     }  
  39.   
  40.     public void setCreatedOn(Date createdOn) {  
  41.         this.createdOn = createdOn;  
  42.     }  
  43.   
  44.     @Override  
  45.     public String toString() {  
  46.         return MessageFormat.format("Blog [blogId={0}, blogName={1}, createdOn={2}]", blogId, blogName, createdOn);  
  47.     }  
  48. }  
 

BlogMapper.java

Java代码   收藏代码
  1. package com.iflytek.dao.mapper;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.ibatis.annotations.Delete;  
  6. import org.apache.ibatis.annotations.Insert;  
  7. import org.apache.ibatis.annotations.Options;  
  8. import org.apache.ibatis.annotations.Result;  
  9. import org.apache.ibatis.annotations.Results;  
  10. import org.apache.ibatis.annotations.Select;  
  11. import org.apache.ibatis.annotations.Update;  
  12.   
  13. import com.iflytek.dao.model.Blog;  
  14.   
  15. /** 
  16.  * @author xdwang 
  17.  *  
  18.  * @ceate 2012-12-10 下午7:30:44 
  19.  *  
  20.  * @description 数据访问层接口,手动添加,基于注解的模式   
  21.  */  
  22. public interface BlogMapper {  
  23.     @Insert("INSERT INTO BLOG(BLOG_NAME, CREATED_ON) VALUES(#{blogName}, #{createdOn})")  
  24.     @Options(useGeneratedKeys = true, keyProperty = "blogId")  
  25.     public void insertBlog(Blog blog);  
  26.   
  27.     @Select("SELECT BLOG_ID AS blogId, BLOG_NAME as blogName, CREATED_ON as createdOn FROM BLOG WHERE BLOG_ID=#{blogId}")  
  28.     public Blog getBlogById(Integer blogId);  
  29.   
  30.     @Select("SELECT * FROM BLOG ")  
  31.     @Results({ @Result(id = true, property = "blogId", column = "BLOG_ID"), @Result(property = "blogName", column = "BLOG_NAME"),  
  32.             @Result(property = "createdOn", column = "CREATED_ON") })  
  33.     public List<Blog> getAllBlogs();  
  34.   
  35.     @Update("UPDATE BLOG SET BLOG_NAME=#{blogName}, CREATED_ON=#{createdOn} WHERE BLOG_ID=#{blogId}")  
  36.     public void updateBlog(Blog blog);  
  37.   
  38.     @Delete("DELETE FROM BLOG WHERE BLOG_ID=#{blogId}")  
  39.     public void deleteBlog(Integer blogId);  
  40.   
  41. }  
 

BlogService.java

Java代码   收藏代码
  1. package com.iflytek.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.ibatis.session.SqlSession;  
  6.   
  7. import com.iflytek.dao.mapper.BlogMapper;  
  8. import com.iflytek.dao.model.Blog;  
  9. import com.iflytek.util.MyBatisUtil;  
  10.   
  11. /** 
  12.  * @author xdwang 
  13.  *  
  14.  * @ceate 2012-12-10 下午7:39:34 
  15.  *  
  16.  * @description 博客业务逻辑层,调用注解的接口实现 
  17.  *  
  18.  */  
  19. public class BlogService {  
  20.   
  21.     public void insertBlog(Blog blog) {  
  22.         SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();  
  23.         //使用注解的时候一定要将XXXMapper注册一下,跟XML配置namespace一样    
  24.         //MyBatisUtil.getSqlSessionFactory().getConfiguration().addMapper(BlogMapper.class);  
  25.         try {  
  26.             BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);  
  27.             blogMapper.insertBlog(blog);  
  28.             sqlSession.commit();  
  29.         } finally {  
  30.             sqlSession.close();  
  31.         }  
  32.     }  
  33.   
  34.     public Blog getBlogById(Integer blogId) {  
  35.         SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();  
  36.         try {  
  37.             BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);  
  38.             return blogMapper.getBlogById(blogId);  
  39.         } finally {  
  40.             sqlSession.close();  
  41.         }  
  42.     }  
  43.   
  44.     public List<Blog> getAllBlogs() {  
  45.         SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();  
  46.         try {  
  47.             BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);  
  48.             return blogMapper.getAllBlogs();  
  49.         } finally {  
  50.             sqlSession.close();  
  51.         }  
  52.     }  
  53.   
  54.     public void updateBlog(Blog blog) {  
  55.         SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();  
  56.         try {  
  57.             BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);  
  58.             blogMapper.updateBlog(blog);  
  59.             sqlSession.commit();  
  60.         } finally {  
  61.             sqlSession.close();  
  62.         }  
  63.     }  
  64.   
  65.     public void deleteBlog(Integer blogId) {  
  66.         SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();  
  67.         try {  
  68.             BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);  
  69.             blogMapper.deleteBlog(blogId);  
  70.             sqlSession.commit();  
  71.         } finally {  
  72.             sqlSession.close();  
  73.         }  
  74.     }  
  75. }  
 

BlogServiceTest.java

Java代码   收藏代码
  1. package com.iflytek.test;  
  2.   
  3. import java.util.Date;  
  4. import java.util.List;  
  5.   
  6. import org.junit.AfterClass;  
  7. import org.junit.Assert;  
  8. import org.junit.BeforeClass;  
  9. import org.junit.Test;  
  10.   
  11. import com.iflytek.dao.model.Blog;  
  12. import com.iflytek.service.BlogService;  
  13.   
  14. /** 
  15.  * @author xdwang 
  16.  *  
  17.  * @ceate 2012-12-10 下午7:42:41 
  18.  *  
  19.  * @description 基于注解的CRUD 测试 
  20.  *  
  21.  */  
  22. public class BlogServiceTest {  
  23.     private static BlogService blogService;  
  24.   
  25.     @BeforeClass  
  26.     public static void setUp() throws Exception {  
  27.         blogService = new BlogService();  
  28.   
  29.     }  
  30.   
  31.     @AfterClass  
  32.     public static void tearDown() throws Exception {  
  33.         blogService = null;  
  34.   
  35.     }  
  36.   
  37.     @Test  
  38.     public void testInsertBlog() {  
  39.         Blog blog = new Blog();  
  40.         blog.setBlogName("test_blog_" + System.currentTimeMillis());  
  41.         blog.setCreatedOn(new Date());  
  42.   
  43.         blogService.insertBlog(blog);  
  44.         Assert.assertTrue(blog.getBlogId() != 0);  
  45.         Blog createdBlog = blogService.getBlogById(blog.getBlogId());  
  46.         Assert.assertNotNull(createdBlog);  
  47.         Assert.assertEquals(blog.getBlogName(), createdBlog.getBlogName());  
  48.     }  
  49.   
  50.     @Test  
  51.     public void testGetBlogById() {  
  52.         Blog blog = blogService.getBlogById(1);  
  53.         Assert.assertNotNull(blog);  
  54.         System.out.println(blog);  
  55.     }  
  56.   
  57.     @Test  
  58.     public void testGetAllBlogs() {  
  59.         List<Blog> blogs = blogService.getAllBlogs();  
  60.         Assert.assertNotNull(blogs);  
  61.         for (Blog blog : blogs) {  
  62.             System.out.println(blog);  
  63.         }  
  64.     }  
  65.   
  66.     @Test  
  67.     public void testUpdateBlog() {  
  68.         long timestamp = System.currentTimeMillis();  
  69.         Blog blog = blogService.getBlogById(2);  
  70.         blog.setBlogName("TestBlogName" + timestamp);  
  71.         blogService.updateBlog(blog);  
  72.         Blog updatedBlog = blogService.getBlogById(2);  
  73.         Assert.assertEquals(blog.getBlogName(), updatedBlog.getBlogName());  
  74.     }  
  75.   
  76.     @Test  
  77.     public void testDeleteBlog() {  
  78.         Blog blog = blogService.getBlogById(4);  
  79.         blogService.deleteBlog(blog.getBlogId());  
  80.         Blog deletedBlog = blogService.getBlogById(4);  
  81.         Assert.assertNull(deletedBlog);  
  82.     }  
  83.   
  84. }  
 

对于简单语句来说,使用注解代码会更加清晰,然后Java 注解对于复杂语句来说就会混乱, 应该限制使用。 因此, 如果你不得不做复杂的事情, 那么最好使用 XML 来映射语句。

 

几个重要的范围和生命周期

1、SqlSessionFactoryBuilder

这个类可以被实例化使用和丢弃。一旦你创建了SqlSessionFactory 后,这个类就不需要存在了。 因此 SqlSessionFactoryBuilder 实例的最佳范围是方法范围 (也就是本地方法变量)。你可以重用 SqlSessionFactoryBuilder来创建多个SqlSessionFactory实例,但是最好的方式是不需要保持它一直存在来保证所有 XML 解析资源,因为还有更重要的事情要做。

2、SqlSessionFactory

一旦被创建,SqlSessionFactory 应该在你的应用执行期间都存在。没有理由来处理或重新创建它。使用 SqlSessionFactory的最佳实践是在应用运行期间不要重复创建多次。这样的操作将被视为是非常糟糕的。因此 SqlSessionFactory 的最佳范围是应用范围。有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。

3、SqlSession

每个线程都应该有它自己的SqlSession 实例。SqlSession的实例不能被共享,也是线程 不安全的。因此最佳的范围是请求或方法范围。绝对不能将 SqlSession 实例的引用放在一个类的静态字段甚至是实例字段中。也绝不能将SqlSession实例的引用放在任何类型的管理范围中, 比如Serlvet架构中的 HttpSession。 如果你现在正用任意的Web框架,要考虑 SqlSession放在一个和 HTTP 请求对象相似的范围内。换句话说,基于收到的HTTP请求,你可以打开了一个SqlSession,然后返回响应,就可以关闭它了。关闭Session很重要,你应该确保使用 finally 块来关闭它。下面的示例就是一个确保 SqlSession 关闭的基本模式:

 

Java代码   收藏代码
  1. SqlSession session = sqlSessionFactory.openSession();  
  2. try {  
  3.   // do work  
  4. } finally {  
  5.   session.close();  
  6. }   
 

 在你的代码中一贯地使用这种模式, 将会保证所有数据库资源都正确地关闭 (假设你没 有通过你自己的连接关闭,这会给 MyBatis 造成一种迹象表明你要自己管理连接资源) 。

4、Mapper 实例

映射器是你创建绑定映射语句的接口。映射器接口的实例可以从 SqlSession 中获得。那 么从技术上来说,当被请求时,任意映射器实例的最宽范围和 SqlSession 是相同的。然而, 映射器实例的最佳范围是方法范围。也就是说,它们应该在使用它们的方法中被请求,然后 就抛弃掉。它们不需要明确地关闭,那么在请求对象中保留它们也就不是什么问题了,这和 SqlSession 相似。你也许会发现,在这个水平上管理太多的资源的话会失控。保持简单,将 映射器放在方法范围内。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值