总结mybatis基础知识

来源:互联网 发布:linux select timeout 编辑:程序博客网 时间:2024/05/22 03:43

MyBatis持久层框架使用总结

     MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。

     iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)。

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

     每个MyBatis应用程序主要都是使用SqlSessionFactory实例的,一个SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。SqlSessionFactoryBuilder可以从一个xml配置文件或者一个预定义的配置类的实例获得。

 1.使用Generator自动生成Dao层,Model层和Mapper层。

    MyBatis Generator下载地址:http://www.mybatis.org/generator/ 

    MyBatis Generator中文介绍:http://generator.sturgeon.mopaas.com/ 

    以下用mybatis-generator-core-1.3.2.jar插件加jdbc数据库连接包自动导出持久层dao包,model包和mapper包。

    需要用到的Java包有: 

       mybatis-generator-core-1.3.2.jar,

       mysql-connector-java-5.1.34.jar,

       ojdbc14-10.2.0.1.0.jar,

       sqljdbc4-4.0.jar。

    配置文件: generator.xml

 View Code

     打开cmd命令行,转到配置文件所在的文件下,执行如下生成语句:

java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite

    命令执行完毕,可以看到对应路径下生成dao包,model包和mapper包文件。

 2.MyBatis框架整合

  1)MyBatis使用参数配置:sqlMapConfig.xml。

    ① 缓存配置(Cache):cacheEnabled:全局开关:默认是true,如果它配成false,其余各个Mapper XML文件配成支持cache也没用。

    ② 延迟加载:

         lazyLoadingEnabled:true使用延迟加载,false禁用延迟加载,默认为true,当禁用时, 所有关联对象都会即时加载。 

         aggressiveLazyLoading:true启用时,当延迟加载开启时访问对象中一个懒对象属性时,将完全加载这个对象的所有懒对象属性。false,当延迟加载时,按需加载对象属性(即访问对象中一个懒对象属性,不会加载对象中其他的懒对象属性)。默认为true。

     ③ multipleResultSetsEnabled:允许和不允许单条语句返回多个数据集(取决于驱动需求)。默认为true。

     ④ useColumnLabel:使用列标签代替列名称。不同的驱动器有不同的做法。参考一下驱动器文档,或者用这两个不同的选项进行测试一下。

     ⑤ useGeneratedKeys:允许JDBC生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。

     ⑥ autoMappingBehavior:指定MyBatis 是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射所有复杂的结果。

    ⑦ defaultExecutorType:配置和设定执行器,SIMPLE执行器执行其它语句。REUSE执行器可能重复使用prepared statements语句,BATCH执行器可以重复执行语句和批量更新。

    ⑧ defaultStatementTimeout:设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时。

    完整sqlMapConfig.xml配置文件如下:

  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   6 <configuration>  7     <settings>  8         <setting name="cacheEnabled" value="true" />  9         <setting name="lazyLoadingEnabled" value="true" /> 10         <setting name="multipleResultSetsEnabled" value="true" /> 11         <setting name="useColumnLabel" value="true" /> 12         <setting name="useGeneratedKeys" value="false" /> 13         <setting name="autoMappingBehavior" value="PARTIAL" /> 14         <setting name="defaultExecutorType" value="SIMPLE" /><!-- SIMPLE REUSE BATCH --> 15         <!-- <setting name="defaultExecutorType" value="BATCH" /> --> 16         <setting name="defaultStatementTimeout" value="25000" /> 17         <setting name="safeRowBoundsEnabled" value="false" /> 18         <setting name="mapUnderscoreToCamelCase" value="false" /> 19         <setting name="localCacheScope" value="SESSION" /> 20         <!-- <setting name="jdbcTypeForNull" value="OTHER" /> --> 21         <setting name="jdbcTypeForNull" value="NULL" /> 22         <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" /> 23     </settings> 24     <typeAliases> 26         <!-- 模块 --> 37         <typeAlias alias="User" type="com.ouc.mkhl.platform.authority.model.User"/>  39         <typeAlias alias="Role" type="com.ouc.mkhl.platform.authority.model.Role"/> 73         <typeAlias alias="Equipment" type="com.ouc.mkhl.platform.basedata.model.Equipment"/> 74         <typeAlias alias="Factory" type="com.ouc.mkhl.platform.basedata.model.Factory"/>152     </typeAliases>153     154     <typeHandlers>155       <typeHandler handler="com.ouc.openplatform.dao.mybatis.SerializableTypeHandler"/>156     </typeHandlers>157 </configuration>

    序列化特殊值处理:SerializableTypeHandler

 View Code

   2)结果集resultMap:

    MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。在MyBatis进行查询映射的时候,其实查询出来的每一个属性都是放在一个对应的Map里面的,其中键是属性名,值则是其对应的值。当提供的返回类型属性是resultType的时候,MyBatis会将Map里面的键值对取出赋给resultType所指定的对象对应的属性。所以其实MyBatis的每一个查询映射的返回类型都是ResultMap,只是当我们提供的返回类型属性是resultType的时候,MyBatis对自动的给我们把对应的值赋给resultType所指定对象的属性,而当我们提供的返回类型是resultMap的时候,因为Map不能很好表示领域模型,我们就需要自己再进一步的把它转化为对应的对象,这常常在复杂查询中很有作用。

    示例:UserBaseResultMap

<resultMap id="UserBaseResultMap" type="User" >    <id column="id" property="id" jdbcType="INTEGER" />    <result column="userName" property="userName" jdbcType="VARCHAR" />    <result column="password" property="password" jdbcType="VARCHAR" />    <result column="email" property="email" jdbcType="VARCHAR" />    <result column="trueName" property="trueName" jdbcType="VARCHAR" />    <result column="sex" property="sex" jdbcType="VARCHAR" />    <result column="age" property="age" jdbcType="INTEGER" />    <result column="telephone" property="telephone" jdbcType="VARCHAR" />  </resultMap>

   model类:User

 View Code

  3)增删改查:

  (1)select查询: 

      ① id:在这个模式下唯一的标识符,可被其它语句引用。

      ② parameterType:传给此语句的参数的完整类名或别名。

      ③ resultType:语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用)

      ④ resultMap:引用的外部resultMap名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用)

      ⑤ flushCache:如果设为true,则会在每次语句调用的时候就会清空缓存。select语句默认设为false。

      ⑥ useCache:如果设为true,则语句的结果集将被缓存。select语句默认设为false。

      ⑦ timeout :设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定。

    示例:查询所有用户信息:selectUsers

<select id="selectUsers" resultMap="UserBaseResultMap">    select id,userName,email from user </select>

   (2) insert插入:saveUser

    此处数据库表使用主键自增,主键为id。

     ① fetchSize:设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定。

     ② statementType:statement,preparedstatement,callablestatement。预准备语句、可调用语句。

     ③ useGeneratedKeys:使用JDBC的getGeneratedKeys方法来获取数据库自己生成的主键(MySQL、SQLSERVER等关系型数据库会有自动生成的字段)。

     ④ keyProperty:标识一个将要被MyBatis设置进getGeneratedKeys的key所返回的值,或者为insert语句使用一个selectKey子元素。

<insert id="saveUser" parameterType="User" >    insert into user (userName, password, email, trueName, sex, age, telephone)    values (#{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},       #{email,jdbcType=VARCHAR}, #{trueName,jdbcType=VARCHAR},       #{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{telephone,jdbcType=VARCHAR})</insert>

    (3)update更新:动态更新SQL:updateUser

  <update id="updateUser" parameterType="User" >    update user    <set >      <if test="userName != null" >        userName = #{userName,jdbcType=VARCHAR},      </if>      <if test="password != null" >        password = #{password,jdbcType=VARCHAR},      </if>      <if test="email != null" >        email = #{email,jdbcType=VARCHAR},      </if>      <if test="trueName != null" >        trueName = #{trueName,jdbcType=VARCHAR},      </if>      <if test="sex != null" >        sex = #{sex,jdbcType=VARCHAR},      </if>      <if test="age != null" >        age = #{age,jdbcType=INTEGER},      </if>      <if test="telephone != null" >        telephone = #{telephone,jdbcType=VARCHAR},      </if>    </set>    where id = #{id,jdbcType=INTEGER}  </update>

    (4)delete删除:deleteUser

<delete id="deleteUser" parameterType="Integer">    delete from user    where id = #{id,jdbcType=INTEGER}</delete>

    (5)sql: Sql元素用来定义一个可以复用的SQL语句段,供其它语句调用。

<sql id="UserBaseColumnList" >    userName, password, email, telephone</sql><select id="getUsers" resultMap="UserBaseResultMap">    select     <include refid="UserBaseColumnList" />    from user</select>

   (6)参数:parameters:MyBatis可以使用基本数据类型和Java的复杂数据类型。
       基本数据类型,String,int,date等。
       使用基本数据类型,只能提供一个参数,所以需要使用Java实体类,或Map类型做参数类型。通过#{}可以直接得到其属性。

      ① 基本数据类型参数:String

<select id="getUserByName" resultType="User" parameterType="String" >    select id, userName, email  from user    where userName = #{userName,jdbcType=VARCHAR}</select>

     Java代码:

public User getUserByName(String name); // 根据用户名获取用户信息

     ② Java实体类型参数:User

<insert id="saveUser" parameterType="User" >    insert into user (userName, password, email, trueName, sex, age, telephone)    values (#{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},       #{email,jdbcType=VARCHAR}, #{trueName,jdbcType=VARCHAR},       #{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{telephone,jdbcType=VARCHAR})</insert>

    Java代码:

public int saveUser(User user); // 插入用户信息

    ③ Map参数:Map<String, Object> recordMap

<select id="selectChildGroupTotalNum" resultType="Integer" >    select count(*) from groupinfo     <trim prefix="WHERE" prefixOverrides="AND|OR">        and id in         <foreach collection="idStr" item="ids" open="(" separator="," close=")">                #{ids}              </foreach>            <if test="name!= null and name!='' " >           and name LIKE CONCAT(CONCAT('%', #{name}),'%')        </if>        <if test="description!= null and description!='' " >           AND description LIKE CONCAT(CONCAT('%', #{description}),'%')        </if>        <if test="type != null and type!=-1 " >           AND type = #{type,jdbcType=INTEGER}        </if>        <if test="category != null and category!=-1 " >           AND category = #{category,jdbcType=INTEGER}        </if>     </trim>   </select>

    Java代码:

//获取子组总记录数public int selectChildGroupTotalNum(Map<String, Object> recordMap);  
Map<String, Object> recordMap = new HashMap<String, Object>();        recordMap.put("idStr", group.getChildgroupids().split(","));        recordMap.put("name", name);        recordMap.put("description", description);        recordMap.put("type", -1);        recordMap.put("category", -1);        childGroupTotalNum = groupDao.selectChildGroupTotalNum(recordMap);

    ④ 多参数:

     方法一:按顺序传递参数。

<!-- 根据参数名查询参数 -->  <select id="selectSensorNobySensorName" resultType="Integer" useCache="false" flushCache="true">     select SensorNo from sensorconfig      where Name = #{0} and TestunitNo = #{1} and LABCODE = #{2}  </select>

      Java代码:

//根据参数名查询参数IDpublic int selectSensorNobySensorName(String sensorName, int testUnitNo, String labCode);

    方法二:接口参数上添加@Param注解。

<select id="selectByUserNameAndVCode" resultMap="UserBaseResultMap">        select id, userName from user        <trim prefix="WHERE" prefixOverrides="AND|OR">            <if test="userName!= null and userName!='' ">                and userName LIKE CONCAT(CONCAT('%', #{userName}),'%')            </if>            <if test="supplierno!= null and supplierno!='' ">                and supplierNo LIKE CONCAT(CONCAT('%', #{supplierno}),'%')            </if>             and supplierNo != 'test'        </trim>        LIMIT #{startIndex},#{pageSize}</select>

    Java代码:

 // 根据用户名和V码查询用户信息 public List<User> selectByUserNameAndVCode(        @Param("userName") String userName,        @Param("supplierno") String supplierno,        @Param("startIndex") int startIndex, @Param("pageSize") int pageSize);

 4)动态SQL语句

    selectKey标签,if标签,if + where的条件判断,if + set的更新语句,if + trim代替where/set标签,trim代替set,choose (when, otherwise),foreach标签。动态SQL语句算是MyBatis最灵活的部分吧,用好了非常方便。

    示例:selectTotalNumByAccountType

<select id="selectTotalNumByAccountType" resultType="Integer" >        select count(*) from user        <trim prefix="WHERE" prefixOverrides="AND|OR">            and id not in             <foreach collection="idStr" item="ids" open="(" separator="," close=")">                   #{ids}                  </foreach>                 <if test="userName!= null and userName!='' ">                and userName LIKE CONCAT(CONCAT('%', #{userName}),'%')            </if>            <if test="supplierno!= null and supplierno!='' ">                and supplierNo LIKE CONCAT(CONCAT('%', #{supplierno}),'%')            </if>             <if test="trueName!= null and trueName!='' ">                and trueName LIKE CONCAT(CONCAT('%', #{trueName}),'%')            </if>            AND accountType = #{accountType}        </trim></select>

    可以查看的文章:

    1. MyBatis学习 之 三、动态SQL语句:http://limingnihao.iteye.com/blog/782190

    2.MyBatis和Hibernate相比,优势在哪里?  https://www.zhihu.com/question/21104468

    3.【持久化框架】Mybatis简介与原理: http://blog.csdn.net/jiuqiyuliang/article/details/45286191

    4.MyBatis学习总结(一)——MyBatis快速入门: http://www.cnblogs.com/xdp-gacl/p/4261895.html

    5.利用mybatis-generator自动生成代码: http://www.cnblogs.com/yjmyzz/p/4210554.html

    6.MyBatis魔法堂:即学即用篇: http://www.cnblogs.com/fsjohnhuang/p/4014819.html

    7.mybatis 使用经验小结: http://www.cnblogs.com/yjmyzz/p/4261024.html

0 0