`
阅读更多

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

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

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

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

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

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

package com.iflytek.util;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * @author xdwang
 * 
 * @ceate 2012-12-10 下午6:30:53
 * 
 * @description MyBatis帮助类,获取SqlSessionFactory
 * 
 */
public class MyBatisUtil {

	private static SqlSessionFactory factory;

	private MyBatisUtil() {
	}

	static {
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader("com/iflytek/resources/mybatis-config.xml");
			// InputStream inputStream =
			// Resources.getResourceAsStream("com/iflytek/resources/mybatis-config.xml");
			// factory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage());
		}
		factory = new SqlSessionFactoryBuilder().build(reader);
	}

	/**
	 * @descrption 获取SqlSessionFactory对象
	 * @author xdwang
	 * @create 2012-12-10下午6:32:24
	 * @return 返回SqlSessionFactory对象
	 */
	public static SqlSessionFactory getSqlSessionFactory() {
		return factory;
	}
}

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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<!-- version: $Id$ -->
<configuration>
	<!-- 引用JDBC属性的配置文件 -->
	<properties resource="database.properties" />

	<settings>
		<!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
		<setting name="useGeneratedKeys" value="true" />
		<setting name="defaultExecutorType" value="REUSE" />
	</settings>

	<environments default="development">
		<environment id="development">
			<!-- 使用JDBC的事务管理 -->
			<transactionManager type="JDBC" />
			<!-- POOLED :JDBC连接对象的数据源连接池的实现,不直接支持第三方数据库连接池 -->
			<dataSource type="POOLED">
				<property name="driver" value="${database.driver}" />
				<property name="url" value="${database.url}" />
				<property name="username" value="${database.username}" />
				<property name="password" value="${database.password}" />
			</dataSource>
		</environment>

	</environments>

	<!-- ORM映射文件 -->
	<mappers>
		<!-- 注解的方式 -->
		<mapper class="com.iflytek.dao.mapper.BlogMapper" />
		<!-- XML的方式 -->
		<mapper resource="com/iflytek/dao/xml/StudentMapper.xml" />
		<!-- 这里对于注解,还可以通过<package name="com.iflytek.dao.mapper"/> -->
	</mappers>
</configuration>

 

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

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/ibatis
database.username=root
database.password=123
 

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

package com.iflytek.dao.model;

import java.text.MessageFormat;
import java.util.Date;

public class Student {
	private Integer id;

	private String name;

	private Date birth;

	private Float score;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name == null ? null : name.trim();
	}

	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}

	public Float getScore() {
		return score;
	}

	public void setScore(Float score) {
		this.score = score;
	}

	@Override
	public String toString() {
		return MessageFormat.format("id:{0},姓名:{1},出生日期:{2},分数:{3}", id, name, birth, score);
	}
}

 StudentExample.java

package com.iflytek.dao.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class StudentExample {
    protected String orderByClause;

    protected boolean distinct;

    protected List<Criteria> oredCriteria;

    public StudentExample() {
        oredCriteria = new ArrayList<Criteria>();
    }

    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    public boolean isDistinct() {
        return distinct;
    }

    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }

    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }

    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;

        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<Criterion>();
        }

        public boolean isValid() {
            return criteria.size() > 0;
        }

        public List<Criterion> getAllCriteria() {
            return criteria;
        }

        public List<Criterion> getCriteria() {
            return criteria;
        }

        protected void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }

        protected void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }

        protected void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }

        protected void addCriterionForJDBCDate(String condition, Date value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            addCriterion(condition, new java.sql.Date(value.getTime()), property);
        }

        protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) {
            if (values == null || values.size() == 0) {
                throw new RuntimeException("Value list for " + property + " cannot be null or empty");
            }
            List<java.sql.Date> dateList = new ArrayList<java.sql.Date>();
            Iterator<Date> iter = values.iterator();
            while (iter.hasNext()) {
                dateList.add(new java.sql.Date(iter.next().getTime()));
            }
            addCriterion(condition, dateList, property);
        }

        protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
        }

        public Criteria andIdIsNull() {
            addCriterion("id is null");
            return (Criteria) this;
        }

        public Criteria andIdIsNotNull() {
            addCriterion("id is not null");
            return (Criteria) this;
        }

        public Criteria andIdEqualTo(Integer value) {
            addCriterion("id =", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotEqualTo(Integer value) {
            addCriterion("id <>", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdGreaterThan(Integer value) {
            addCriterion("id >", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdGreaterThanOrEqualTo(Integer value) {
            addCriterion("id >=", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdLessThan(Integer value) {
            addCriterion("id <", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdLessThanOrEqualTo(Integer value) {
            addCriterion("id <=", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdIn(List<Integer> values) {
            addCriterion("id in", values, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotIn(List<Integer> values) {
            addCriterion("id not in", values, "id");
            return (Criteria) this;
        }

        public Criteria andIdBetween(Integer value1, Integer value2) {
            addCriterion("id between", value1, value2, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotBetween(Integer value1, Integer value2) {
            addCriterion("id not between", value1, value2, "id");
            return (Criteria) this;
        }

        public Criteria andNameIsNull() {
            addCriterion("name is null");
            return (Criteria) this;
        }

        public Criteria andNameIsNotNull() {
            addCriterion("name is not null");
            return (Criteria) this;
        }

        public Criteria andNameEqualTo(String value) {
            addCriterion("name =", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameNotEqualTo(String value) {
            addCriterion("name <>", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameGreaterThan(String value) {
            addCriterion("name >", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameGreaterThanOrEqualTo(String value) {
            addCriterion("name >=", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameLessThan(String value) {
            addCriterion("name <", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameLessThanOrEqualTo(String value) {
            addCriterion("name <=", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameLike(String value) {
            addCriterion("name like", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameNotLike(String value) {
            addCriterion("name not like", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameIn(List<String> values) {
            addCriterion("name in", values, "name");
            return (Criteria) this;
        }

        public Criteria andNameNotIn(List<String> values) {
            addCriterion("name not in", values, "name");
            return (Criteria) this;
        }

        public Criteria andNameBetween(String value1, String value2) {
            addCriterion("name between", value1, value2, "name");
            return (Criteria) this;
        }

        public Criteria andNameNotBetween(String value1, String value2) {
            addCriterion("name not between", value1, value2, "name");
            return (Criteria) this;
        }

        public Criteria andBirthIsNull() {
            addCriterion("birth is null");
            return (Criteria) this;
        }

        public Criteria andBirthIsNotNull() {
            addCriterion("birth is not null");
            return (Criteria) this;
        }

        public Criteria andBirthEqualTo(Date value) {
            addCriterionForJDBCDate("birth =", value, "birth");
            return (Criteria) this;
        }

        public Criteria andBirthNotEqualTo(Date value) {
            addCriterionForJDBCDate("birth <>", value, "birth");
            return (Criteria) this;
        }

        public Criteria andBirthGreaterThan(Date value) {
            addCriterionForJDBCDate("birth >", value, "birth");
            return (Criteria) this;
        }

        public Criteria andBirthGreaterThanOrEqualTo(Date value) {
            addCriterionForJDBCDate("birth >=", value, "birth");
            return (Criteria) this;
        }

        public Criteria andBirthLessThan(Date value) {
            addCriterionForJDBCDate("birth <", value, "birth");
            return (Criteria) this;
        }

        public Criteria andBirthLessThanOrEqualTo(Date value) {
            addCriterionForJDBCDate("birth <=", value, "birth");
            return (Criteria) this;
        }

        public Criteria andBirthIn(List<Date> values) {
            addCriterionForJDBCDate("birth in", values, "birth");
            return (Criteria) this;
        }

        public Criteria andBirthNotIn(List<Date> values) {
            addCriterionForJDBCDate("birth not in", values, "birth");
            return (Criteria) this;
        }

        public Criteria andBirthBetween(Date value1, Date value2) {
            addCriterionForJDBCDate("birth between", value1, value2, "birth");
            return (Criteria) this;
        }

        public Criteria andBirthNotBetween(Date value1, Date value2) {
            addCriterionForJDBCDate("birth not between", value1, value2, "birth");
            return (Criteria) this;
        }

        public Criteria andScoreIsNull() {
            addCriterion("score is null");
            return (Criteria) this;
        }

        public Criteria andScoreIsNotNull() {
            addCriterion("score is not null");
            return (Criteria) this;
        }

        public Criteria andScoreEqualTo(Float value) {
            addCriterion("score =", value, "score");
            return (Criteria) this;
        }

        public Criteria andScoreNotEqualTo(Float value) {
            addCriterion("score <>", value, "score");
            return (Criteria) this;
        }

        public Criteria andScoreGreaterThan(Float value) {
            addCriterion("score >", value, "score");
            return (Criteria) this;
        }

        public Criteria andScoreGreaterThanOrEqualTo(Float value) {
            addCriterion("score >=", value, "score");
            return (Criteria) this;
        }

        public Criteria andScoreLessThan(Float value) {
            addCriterion("score <", value, "score");
            return (Criteria) this;
        }

        public Criteria andScoreLessThanOrEqualTo(Float value) {
            addCriterion("score <=", value, "score");
            return (Criteria) this;
        }

        public Criteria andScoreIn(List<Float> values) {
            addCriterion("score in", values, "score");
            return (Criteria) this;
        }

        public Criteria andScoreNotIn(List<Float> values) {
            addCriterion("score not in", values, "score");
            return (Criteria) this;
        }

        public Criteria andScoreBetween(Float value1, Float value2) {
            addCriterion("score between", value1, value2, "score");
            return (Criteria) this;
        }

        public Criteria andScoreNotBetween(Float value1, Float value2) {
            addCriterion("score not between", value1, value2, "score");
            return (Criteria) this;
        }
    }

    public static class Criteria extends GeneratedCriteria {

        protected Criteria() {
            super();
        }
    }

    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        private String typeHandler;

        public String getCondition() {
            return condition;
        }

        public Object getValue() {
            return value;
        }

        public Object getSecondValue() {
            return secondValue;
        }

        public boolean isNoValue() {
            return noValue;
        }

        public boolean isSingleValue() {
            return singleValue;
        }

        public boolean isBetweenValue() {
            return betweenValue;
        }

        public boolean isListValue() {
            return listValue;
        }

        public String getTypeHandler() {
            return typeHandler;
        }

        protected Criterion(String condition) {
            super();
            this.condition = condition;
            this.typeHandler = null;
            this.noValue = true;
        }

        protected Criterion(String condition, Object value, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.typeHandler = typeHandler;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }

        protected Criterion(String condition, Object value) {
            this(condition, value, null);
        }

        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.typeHandler = typeHandler;
            this.betweenValue = true;
        }

        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}

 StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.iflytek.dao.mapper.StudentMapper" >
  <resultMap id="BaseResultMap" type="com.iflytek.dao.model.Student" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="birth" property="birth" jdbcType="DATE" />
    <result column="score" property="score" jdbcType="REAL" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    id, name, birth, score
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.iflytek.dao.model.StudentExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from tbl_student
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from tbl_student
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from tbl_student
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.iflytek.dao.model.StudentExample" >
    delete from tbl_student
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.iflytek.dao.model.Student" >
    <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into tbl_student (name, birth, score)
    values (#{name,jdbcType=VARCHAR}, #{birth,jdbcType=DATE}, #{score,jdbcType=REAL})
  </insert>
  <insert id="insertSelective" parameterType="com.iflytek.dao.model.Student" >
    <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into tbl_student
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="name != null" >
        name,
      </if>
      <if test="birth != null" >
        birth,
      </if>
      <if test="score != null" >
        score,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="birth != null" >
        #{birth,jdbcType=DATE},
      </if>
      <if test="score != null" >
        #{score,jdbcType=REAL},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.iflytek.dao.model.StudentExample" resultType="java.lang.Integer" >
    select count(*) from tbl_student
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update tbl_student
    <set >
      <if test="record.id != null" >
        id = #{record.id,jdbcType=INTEGER},
      </if>
      <if test="record.name != null" >
        name = #{record.name,jdbcType=VARCHAR},
      </if>
      <if test="record.birth != null" >
        birth = #{record.birth,jdbcType=DATE},
      </if>
      <if test="record.score != null" >
        score = #{record.score,jdbcType=REAL},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update tbl_student
    set id = #{record.id,jdbcType=INTEGER},
      name = #{record.name,jdbcType=VARCHAR},
      birth = #{record.birth,jdbcType=DATE},
      score = #{record.score,jdbcType=REAL}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.iflytek.dao.model.Student" >
    update tbl_student
    <set >
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="birth != null" >
        birth = #{birth,jdbcType=DATE},
      </if>
      <if test="score != null" >
        score = #{score,jdbcType=REAL},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.iflytek.dao.model.Student" >
    update tbl_student
    set name = #{name,jdbcType=VARCHAR},
      birth = #{birth,jdbcType=DATE},
      score = #{score,jdbcType=REAL}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>
 

StudentMapper.java

package com.iflytek.dao.mapper;

import com.iflytek.dao.model.Student;
import com.iflytek.dao.model.StudentExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface StudentMapper {
    int countByExample(StudentExample example);

    int deleteByExample(StudentExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    int insertSelective(Student record);

    List<Student> selectByExample(StudentExample example);

    Student selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") Student record, @Param("example") StudentExample example);

    int updateByExample(@Param("record") Student record, @Param("example") StudentExample example);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}
 

StudentService.java

package com.iflytek.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.iflytek.dao.mapper.StudentMapper;
import com.iflytek.dao.model.Student;
import com.iflytek.dao.model.StudentExample;
import com.iflytek.util.MyBatisUtil;

/**
 * 
 * @author xdwang
 * 
 * @ceate 2012-12-10 下午6:33:26
 * 
 * @description 业务逻辑层,Mapper和XML是通过generator自动生成的
 * 
 */
public class StudentService {

	/**
	 * @descrption 添加
	 * @author xdwang
	 * @create 2012-12-10下午6:42:48
	 * @param student
	 *            学生实体
	 * @return 是否成功
	 */
	public boolean insertStudent(Student student) {
		boolean flag = false;
		SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			int result = studentMapper.insert(student);
			if (result > 0) {
				flag = true;
			}
			sqlSession.commit();
		} finally {
			sqlSession.close();
		}
		return flag;
	}

	/**
	 * @descrption 根据学生id获取学生实体信息
	 * @author xdwang
	 * @create 2012-12-10下午6:46:09
	 * @param studentId
	 *            学生id
	 * @return 学生实体信息
	 */
	public Student getStudentById(int studentId) {
		SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
		try {
			StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class);
			return StudentMapper.selectByPrimaryKey(studentId);
		} finally {
			sqlSession.close();
		}
	}

	/**
	 * @descrption 获取所有学生信息集合
	 * @author xdwang
	 * @create 2012-12-10下午6:46:55
	 * @return 学生集合
	 */
	public List<Student> getAllStudents() {
		SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
		try {
			StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class);
			return StudentMapper.selectByExample(new StudentExample());
		} finally {
			sqlSession.close();
		}
	}

	/**
	 * @descrption 更新学生信息
	 * @author xdwang
	 * @create 2012-12-10下午6:47:13
	 * @param Student
	 *            学生实体信息
	 * @return 更新成功与否
	 */
	public boolean updateStudent(Student Student) {
		SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
		boolean flag = false;
		try {
			StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class);
			int result = StudentMapper.updateByPrimaryKey(Student);
			if (result > 0) {
				flag = true;
			}
			sqlSession.commit();
		} finally {
			sqlSession.close();
		}
		return flag;

	}

	/**
	 * @descrption 根据学生id删除学生信息
	 * @author xdwang
	 * @create 2012-12-10下午6:49:05
	 * @param studentId
	 *            学生id
	 * @return 删除成功与否
	 */
	public boolean deleteStudent(int studentId) {
		SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
		boolean flag = false;
		try {
			StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class);
			int result = StudentMapper.deleteByPrimaryKey(studentId);
			if (result > 0) {
				flag = true;
			}
			sqlSession.commit();
		} finally {
			sqlSession.close();
		}
		return flag;
	}

}

 

StudentServiceTest.java

package com.iflytek.test;

import java.util.Date;
import java.util.List;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.iflytek.dao.model.Student;
import com.iflytek.service.StudentService;

/**
 * @author xdwang
 * 
 * @ceate 2012-12-10 下午7:02:08
 * 
 * @description 测试业务逻辑
 * 
 */
public class StudentServiceTest {
	private static StudentService studentService;

	@BeforeClass
	public static void setup() {
		studentService = new StudentService();
	}

	@AfterClass
	public static void teardown() {
		studentService = null;
	}

	@Test
	public void testInsertStudent() {
		Student student = new Student();
		student.setName("xwang");
		student.setBirth(new Date());
		student.setScore((float) 99.5);
		System.out.println(studentService.insertStudent(student));
	}

	@Test
	public void testGetStudentById() {
		Student student = studentService.getStudentById(1);
		Assert.assertNotNull(student);
		System.out.println(student);
	}

	@Test
	public void testGetAllStudents() {
		List<Student> students = studentService.getAllStudents();
		Assert.assertNotNull(students);
		for (Student student : students) {
			System.out.println(student);
		}
	}

	@Test
	public void testUpdateStudent() {
		Student student = studentService.getStudentById(1);
		student.setName("xdwang03");
		System.out.println(studentService.deleteStudent(1));
	}

	@Test
	public void testDeleteStudent() {
		System.out.println(studentService.deleteStudent(1));
	}

}

 

二、注解
Blog.java

package com.iflytek.dao.model;

import java.text.MessageFormat;
import java.util.Date;

/**
 * @author xdwang
 * 
 * @ceate 2012-12-10 下午7:29:08
 * 
 * @description 博客实体类,手动创建
 * 
 */
public class Blog {

	private Integer blogId;
	private String blogName;
	private Date createdOn;

	public Integer getBlogId() {
		return blogId;
	}

	public void setBlogId(Integer blogId) {
		this.blogId = blogId;
	}

	public String getBlogName() {
		return blogName;
	}

	public void setBlogName(String blogName) {
		this.blogName = blogName;
	}

	public Date getCreatedOn() {
		return createdOn;
	}

	public void setCreatedOn(Date createdOn) {
		this.createdOn = createdOn;
	}

	@Override
	public String toString() {
		return MessageFormat.format("Blog [blogId={0}, blogName={1}, createdOn={2}]", blogId, blogName, createdOn);
	}
}

 

BlogMapper.java

package com.iflytek.dao.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.iflytek.dao.model.Blog;

/**
 * @author xdwang
 * 
 * @ceate 2012-12-10 下午7:30:44
 * 
 * @description 数据访问层接口,手动添加,基于注解的模式  
 */
public interface BlogMapper {
	@Insert("INSERT INTO BLOG(BLOG_NAME, CREATED_ON) VALUES(#{blogName}, #{createdOn})")
	@Options(useGeneratedKeys = true, keyProperty = "blogId")
	public void insertBlog(Blog blog);

	@Select("SELECT BLOG_ID AS blogId, BLOG_NAME as blogName, CREATED_ON as createdOn FROM BLOG WHERE BLOG_ID=#{blogId}")
	public Blog getBlogById(Integer blogId);

	@Select("SELECT * FROM BLOG ")
	@Results({ @Result(id = true, property = "blogId", column = "BLOG_ID"), @Result(property = "blogName", column = "BLOG_NAME"),
			@Result(property = "createdOn", column = "CREATED_ON") })
	public List<Blog> getAllBlogs();

	@Update("UPDATE BLOG SET BLOG_NAME=#{blogName}, CREATED_ON=#{createdOn} WHERE BLOG_ID=#{blogId}")
	public void updateBlog(Blog blog);

	@Delete("DELETE FROM BLOG WHERE BLOG_ID=#{blogId}")
	public void deleteBlog(Integer blogId);

}

 

BlogService.java

package com.iflytek.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.iflytek.dao.mapper.BlogMapper;
import com.iflytek.dao.model.Blog;
import com.iflytek.util.MyBatisUtil;

/**
 * @author xdwang
 * 
 * @ceate 2012-12-10 下午7:39:34
 * 
 * @description 博客业务逻辑层,调用注解的接口实现
 * 
 */
public class BlogService {

	public void insertBlog(Blog blog) {
		SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
		//使用注解的时候一定要将XXXMapper注册一下,跟XML配置namespace一样  
		//MyBatisUtil.getSqlSessionFactory().getConfiguration().addMapper(BlogMapper.class);
		try {
			BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
			blogMapper.insertBlog(blog);
			sqlSession.commit();
		} finally {
			sqlSession.close();
		}
	}

	public Blog getBlogById(Integer blogId) {
		SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
		try {
			BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
			return blogMapper.getBlogById(blogId);
		} finally {
			sqlSession.close();
		}
	}

	public List<Blog> getAllBlogs() {
		SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
		try {
			BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
			return blogMapper.getAllBlogs();
		} finally {
			sqlSession.close();
		}
	}

	public void updateBlog(Blog blog) {
		SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
		try {
			BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
			blogMapper.updateBlog(blog);
			sqlSession.commit();
		} finally {
			sqlSession.close();
		}
	}

	public void deleteBlog(Integer blogId) {
		SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
		try {
			BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
			blogMapper.deleteBlog(blogId);
			sqlSession.commit();
		} finally {
			sqlSession.close();
		}
	}
}

 

BlogServiceTest.java

package com.iflytek.test;

import java.util.Date;
import java.util.List;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.iflytek.dao.model.Blog;
import com.iflytek.service.BlogService;

/**
 * @author xdwang
 * 
 * @ceate 2012-12-10 下午7:42:41
 * 
 * @description 基于注解的CRUD 测试
 * 
 */
public class BlogServiceTest {
	private static BlogService blogService;

	@BeforeClass
	public static void setUp() throws Exception {
		blogService = new BlogService();

	}

	@AfterClass
	public static void tearDown() throws Exception {
		blogService = null;

	}

	@Test
	public void testInsertBlog() {
		Blog blog = new Blog();
		blog.setBlogName("test_blog_" + System.currentTimeMillis());
		blog.setCreatedOn(new Date());

		blogService.insertBlog(blog);
		Assert.assertTrue(blog.getBlogId() != 0);
		Blog createdBlog = blogService.getBlogById(blog.getBlogId());
		Assert.assertNotNull(createdBlog);
		Assert.assertEquals(blog.getBlogName(), createdBlog.getBlogName());
	}

	@Test
	public void testGetBlogById() {
		Blog blog = blogService.getBlogById(1);
		Assert.assertNotNull(blog);
		System.out.println(blog);
	}

	@Test
	public void testGetAllBlogs() {
		List<Blog> blogs = blogService.getAllBlogs();
		Assert.assertNotNull(blogs);
		for (Blog blog : blogs) {
			System.out.println(blog);
		}
	}

	@Test
	public void testUpdateBlog() {
		long timestamp = System.currentTimeMillis();
		Blog blog = blogService.getBlogById(2);
		blog.setBlogName("TestBlogName" + timestamp);
		blogService.updateBlog(blog);
		Blog updatedBlog = blogService.getBlogById(2);
		Assert.assertEquals(blog.getBlogName(), updatedBlog.getBlogName());
	}

	@Test
	public void testDeleteBlog() {
		Blog blog = blogService.getBlogById(4);
		blogService.deleteBlog(blog.getBlogId());
		Blog deletedBlog = blogService.getBlogById(4);
		Assert.assertNull(deletedBlog);
	}

}

 

对于简单语句来说,使用注解代码会更加清晰,然后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 关闭的基本模式:

 

SqlSession session = sqlSessionFactory.openSession();
try {
  // do work
} finally {
  session.close();
} 
 

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

4 Mapper 实例

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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics