关于Mybatis的几件小事(一)

2019-06-03  本文已影响0人  一条路上的咸鱼

一、Mybatis简介

1.Mybatis简介

2.为什么使用MyBatis

3.SqlSession

二、全局配置文件

1.properties属性

dbconfig.properties文件内容

driver=com.mysql.jdbc.cj.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8   
username=root
password=root

在全局配置文件中进行如下配置

<properties resource="dbconfig.properties"></properties>

2.settings设置

<settings>
      <setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
设置参数 描述 有效值 默认值
cacheEnabled 改配置影响的所有映射器中配置的缓存的全局开关 true | false true
lazyLoadingEnabled 延迟加载的全局开关,开启后,所有关联的对象都会延时加载。特定关联关系中可通过设置fetchType属性来覆盖本配置 true | false false
useColumnLabel 使用列标签代替列名。不同的驱动在这方面会有不同的表现,具体可参考相关驱动文档或通过测试这两种不同的模式来观察所用驱动的结果 true | false true
defaultStatementTimeout 设置超时时间,决定驱动等待数据库响应的秒数 任意合理的int值 null(不进行限制)
mapUnderscoreToCamelCase 是否开启自动驼峰命名规则映射 true | false false

3.typeAliases别名处理器

<typeAliases>
    <typeAlias type="com.desperado.entity.Employee" alias="employee"/>
    <typeAlias type="com.desperado.entity.Departemnt" alias="department"/>
</typeAliases>
<typeAliases>
      <package name="com.desperado.entity" /> 
</typeAliases>
@Alias("emp")
public class Employee{}

-MyBatis已经为许多常见的Java类型内建了相应的别名,他们都是大小写不敏感的,起别名时要避免这些。

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

4.typeHandlers类型处理器

无论MyBatis在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时,都会用类型处理器将获取的值以合适的方式转换成Java类型。

类型处理器 Java类型 JDBC类型
BooleanTypeHandler java.lang.Boolean,boolean 数据库兼容的BOOLEAN
ByteTypeHandler java.lang.Byte,byte 数据库兼容的NUMERIC或BYTE
ShortTypeHandler java.lang.Short,short 数据库兼容的NUMERIC或SHORT INTEGER
IntegerTypeHandler java.lang.Integer,int 数据库兼容的NUMERIC或INTEGER
LongTypeHandler java.lang.Long,long 数据库兼容的NUMERIC或LONG INTEGER
FloatTypeHandler java.lang.Float,float 数据库兼容的NUMERIC或FLOAT
DoubleTypeHandler java.lang.Double,double 数据库兼容的NUMERIC或DOUBLE
BigDecimalTypeHandler java.math.BigDecimal 数据库兼容的NUMERIC或DECIMAL
StringTypeHandler java.lang.String CHAR、VARCHAR

5.日期类型的处理

<typeHandlers>
    <typeHandler handler="org.apache.ibatis.type.InstantTypeHandler"/>
    <typeHandler handler="org.apache.ibatis.type.LocalDateTimeTypeHandler"/>
    <typeHandler handler="org.apache.ibatis.type.LocalDateTypeHandler"/>
    <typeHandler handler="org.apache.ibatis.type.LocalTimeTypeHandler"/>
    <typeHandler handler="org.apache.ibatis.type.OffsetDateTimeTypeHandler"/>
    <typeHandler handler="org.apache.ibatis.type.OffsetTimeTypeHandler"/>
    <typeHandler handler="org.apache.ibatis.type.ZonedDateTimeTypeHandler"/>
    <typeHandler handler="org.apache.ibatis.type.YearTypeHandler"/>
    <typeHandler handler="org.apache.ibatis.type.MonthTypeHandler"/>
    <typeHandler handler="org.apache.ibatis.type.YearMonthTypeHandler"/>
    <typeHandler handler="org.apache.ibatis.type.JapaneseDateTypeHandler"/>
</typeHandlers>

6.自定义类型处理器

7.plugins插件

8.environments环境

1.指定具体环境
<environments default="development">
    <environment id="development">
          <transactionManager type="JDBC" />
          <dataSource type="POOLED">
                  <property name="driver" value="${dept.driver}" / >
                  <property name="url" value="${dept.url} "/ >
                  <property name="username" value="${dept.username}" / >
                  <property name="password" value="${dept.password}" / >
          <dataSource>
    </environmet>

    <environment id="test">
          <transactionManager type="JDBC" />
          <dataSource type="POOLED">
                  <property name="driver" value="${test.driver}" / >
                  <property name="url" value="${test.url} "/ >
                  <property name="username" value="${test.username}" / >
                  <property name="password" value="${test.password}" / >
          <dataSource>
    </environmet>
</environments>
2.transactionManager

type值取值有三种类型 JDBC|MANAGED|自定义

3.dataSource

type有四种取值 UNPOOLED|POOLED|JNDI|自定义

9.databaseIdProvider环境

<databaseIdProvider type="DB_VENDOR">
      <property name="MySQL" value="mysql"/>
      <property name="Oracle" vale="oracle"/>
      <property name="SQL Server" value="sqlserver" />
</databaseIdProvider>

<select Id="getUserById" result="User"
        parameterType="Integer" databaseId="mysql">
      select * from user where id =#{id}
</select>

10.mapper映射

<mappers>
    <mapper resource="mybatis/mapper/PersonDao.xml" />
    <mapper url="file:///D:/userDao.xml" />
    <mapper class="com.desperado.dao.UserDao" />
</mappers>
<mappers>
    <package name="com.desperado.dao" />
</mappers>

三、映射文件

映射文件指导着MyBatis如何进行数据库的增删改查,有着非常重要的意义:

1.insert、update、delete元素

属性 说明
id 命名空间中的唯一标志符
parameterType 将要传入语句的参数的完全限定类名或别名。这个属性是可选的,因为MyBatis可以通过TypeHandler推断出具体传入语句的参数类型,默认为unset。
flushCache 将其设置为true,任何时候只要语句被调用,都会导致本地缓存和二级缓存都被清空,默认值true(对应插入、删除和更新语句)。
timeout 这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认为unset(依赖驱动)
statementType STATEMENT,PREPARED或CALLABLE的一个。这会让MyBatis分别饰演Statement、PreparedStatement或CallableStatement,默认值:PREPARED
useGeneratorKeys (仅对insert和update有效)这会让MyBatis使用JDBC的getGeneratorKeys方法取出由数据库内部生成的主键,默认值false
keyProperty (仅对insert和update有效)唯一标记一个属性,MyBatis会通过getGeneratedKeys的返回值或者通过insert语句的selectKey子元素设置它的键值,默认unset
keyColumn (仅对insert和update有效)通过生成的键值设置表中的列名,这个设置紧张模型数据库是必须的,当主键列不是表中的第一列的时候需要设置,如果希望得到多个生成的列,也可以是逗号分隔的属性名称列表。
databaseId 如果配置了databaseIdProvider,MyBatis会加载所有的不带databaseId或匹配当前databaseId的语句;如果带或者不带的语句都有,则不带的会被忽略。

2.主键生成方式

<insert id="insertCustomer" databaseId="mysql"     
    useGeneratedKeys="true" keyProperty="id">
    insert into customer(name,age,email) values (#{name},#{age},#{email})
</insert>
<insert id="insertCustomer" databaseId="oracle" parameterType=“customer”>

    <selectKey order="BEFORE" keyProperty="id" resultType="_int" >
          select crm_seq.nextval from dual
    </selectKey>
    insert into customer(id,name,age,email) values (#{id},#{name},#{age},#{email})
</insert>
属性 说明
keyProperty selectKey语句结果应该被设置的目标属性
keyColumn 匹配属性的返回结果集中的列名称
resultType 结果的类型,MyBatis通常可以推断出来,但是为了更加确定写上也不会有什么问题。MyBatis允许任何简单类型用作主键的类型,包括字符串。
order 可以被设置为BEFORE或AFTER,如果设置为BEFORE,那么它会首先选择主键,设置keyProperty然后执行插入语句。如果设置为After,那么先执行插入语句,然后是selectKey执行。
statementType 与前面相同,MyBatis支持STATEMENT,PREPARED和CALLABLE语句的映射类型,分布代表PreparedStatement和CallableStatement

3.参数传递

4.参数处理

#{property,javaType=int,jdbcType=NUMERIC}

#{height,javaType=double,jdbcType=NUMERIC,numericScale=2}

-javaType通常可以从参数对象中去确定。
-如果null被当做值来传递,对应所有可能为空的列,jdbcType需要被设置。
-对于数值类型,还可以设置小数点后保留的位数
-mode属性允许指定IN、OUT和INOUT属性。如果参数为OUT或INOUT,参数对象属性的真实值会被改变,就像在获取输出参数时所期望的那些。

5.select语句

属性 说明
id 命名空间中的唯一标志符
parameterType 将要传入语句的参数的完全限定类名或别名。这个属性是可选的,因为MyBatis可以通过TypeHandler推断出具体传入语句的参数类型,默认为unset。
resultType 返回的期望类型的完全限定名或别名。注意如果是集合,那应该是集合可以包含的类型,而不是集合本身,本属性和resultMap不能同时使用。
flushCache 将其设置为true,任何时候只要语句被调用,都会导致本地缓存和二级缓存都被清空,默认值false。
useCache 将其设置为true,将会导致本条语句的结果被二级缓存进行缓存,默认值:true
timeout 这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认为unset(依赖驱动)
fetchSize 影响驱动程序每次批量返回的结果行数。默认值unset(依赖驱动)
statementType STATEMENT,PREPARED或CALLABLE的一个。这会让MyBatis分别饰演Statement、PreparedStatement或CallableStatement,默认值:PREPARED
resultSetType FORWARD_ONLY、SCROLL_SENSITIVE或者SCROLL_INSENSITIVE中的一个,默认值为unset(依赖驱动)
databaseId 如果配置了databaseIdProvider,MyBatis会加载所有的不带databaseId或匹配当前databaseId的语句;如果带或者不带的语句都有,则不带的会被忽略。
resultOrdered 这个设置仅针对嵌套结果select语句适用;如果为true,就假设包含了嵌套结果集或是分组,这样当返回一个主结果行,就不会发生有对前面结果集引用的情况,这就使得在获取嵌套的结果集的时候不至于导致内存不足,默认值false
resultSets 这个设置仅对多结果集的情况适用,它将雷人语句执行后返回的结果集并给每个结果集一个名称,名称是逗号分隔的。

6.自动映射

7.resultMap

8.Id&Result

属性 说明
property 映射到列结果的字段或属性。
column 数据表的列名
javaType 一个Java类的完全限定名或一个类型别名
jdbcType JDBC类型是仅仅需要对插入、更新和删除操作可能为空的列进行处理
typeHandler 类型处理器

9.association

<resultMap type="com.desperado.bean.Lock" id="myLock">
    <id column="id" property="id" />
    <id column="lockName" property="lockName" />
    <id column="key_id" property="key.id" />
    <id column="keyName" property="key.keyName" />
</resultMap>
<resultMap type="com.desperado.bean.Lock" id="myLock2">
    <id column="id" property="id" />
    <result column="lockName" property="lockName" />
    <association property="key" javaType="com.desperado.bean.Key">
        <id column="key_id" property="id" />
        <result column="keyName" property="keyName" />
    </association>
</resultMap>

<resultMap type="com.desperado.bean.Lock" id="myLock3">
    <id column="id" property="id" />
    <result column="lockName" property="lockName" />
    <association property="key" 
        select="com.desperado.dao.KeyMapper.getKeyById"  
        column="key_id">
    </association>
</resultMap>
<settings>
    <select name="lazyLoadingEnabled" value="true" />
    <setting name="aggressiveLazyLoading" value="false"  />
</settings>

10.Collection

<select id="getDeptById" resultMap="MyDept">
      select d.id d_id,
             d.dept_name d_deptName,
             e.id e_id,
             e.last_name e_lastName,
             e.email e_email,
             e.gender e_gender,
             e.dept_id e_deptId
      from depertment d 
      left join employee e on e.dept_id = d.id
      where d.id = #{id}
</select>

-使用collection之后

<resultMap type="com.desperado.bean.Department" id="MyDept">
    <id column="d_id" property="id" />
    <result column="d_deptName" property="deptName" />
    <collection property="emps" 
        ofType="com.desperado.bean.Employee"  
        columnPrefix="e_">
         <id column="id" property="id" />
         <id column="lastName" property="lastName" />
         <id column="email" property="email" />
         <id column="gender" property="gender"/>
    </collection>
</resultMap>
<resultMap type="com.desperado.bean.Department" id="MyDeptStep">
    <id column="id" property="id" />
    <result column="dept_name" property="deptName" />
    <collection property="emps" 
        select="com.desperado.dao.EmployeeMapper.getEmpsByDeptId"  
        column="id">
    </collection>
</resultMap>

11.扩展-多列值封装map传递

<resultMap type="com.desperado.bean.Department" id="MyDeptStep">
    <id column="id" property="id" />
    <result column="dept_name" property="deptName" />
    <collection property="emps" 
        select="com.desperado.dao.EmployeeMapper.getEmpsByDeptId"  
        column="{deptId=id}">
    </collection>
</resultMap>

四、动态SQL

1.动态SQL简介

2.Multi-db vendor 支持

<databaseIdProvider type="DB_VENDOR">
    <property name="MySQL" value="mysql" />
    <property name="Oracle" value="oracle" />
</databaseIdProvider>
<select id="getEmpPage" resultType="com.desperado.bean.Employee">
       <if test="_databaseId =='mysql' ">
          select * from employee where limit 0,5
       </if>

       <if test="_databaseId == 'oracle' ">
            select * from (select e.*,rownum as r1 from employee e where rownum &lt;=5) where r1 &gt;= 1;
       </if>  
</select>
上一篇 下一篇

猜你喜欢

热点阅读