mybatis系列:三、配置详解

SqlMapConfig.xml配置详解

具体配置如下
properties(属性)
settings(全局配置参数)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境集合属性对象)
environment(环境子属性对象)
transactionManager(事务管理)
dataSource(数据源)
mappers(映射器)

<?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">

<configuration>
    <!-- 在classpath下定义属性文件引入 -->
    <properties resource="db.properties"/>

	<!-- mybatis的全局配置参数 -->
    <settings>
        <!-- 延迟加载的总开关 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 设置为false,实现按需求加载 -->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

    <!-- 别名 -->
    <typeAliases>
        <!-- 单个指定 -->
        <typeAlias type="cn.ade.domain.User" alias="user"/>

        <!-- 批量指定,扫描包下的所有类,别名为类名大写或者小写都可以 -->
        <package name="cn.ade.domain"/>
    </typeAliases>

    <!-- 与spring整合之后,environments将被废除 -->
    <environments default="development">
        <!-- 可以配置多个环境 -->
        <environment id="development">
            <!-- 使用JDBC事务管理 -->
            <transactionManager type="JDBC"/>
            <!-- 数据库连接池,使用mybatis自带的连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>

    <!-- 加载mapper.xml -->
    <mappers>
        <!-- 指定classpath下的文件 -->
        <!--<mapper resource="sqlmap/User.xml"/>-->

		<!-- 使用绝对路径 -->
        <!--<mapper url="file:///D:\workspace\mybatis\src\main\resources\sqlmap" />-->

        <!-- 使用mapper接口类路径,通过mapper.java进行映射,映射文件和类路径保持一致 -->
        <!--<mapper class="cn.adepper.UserMapper"/>-->

        <!-- 通过包扫描进行映射 -->
        <package name="cn.ade.mapper"/>
    </mappers>
</configuration>

属性

mybatis加载属性的顺序:

  • 加载properties元素体中定义的属性
  • 加载properties元素中resource或url加载的属性
  • 加载parameterType传递的属性

加载规则:后面加载的会覆盖前面加载的同名属性

全局参数settings

别名typeAliases

mybatis除了可以自定义别名,也有一些默认支持的别名
默认支持别名

别名映射的类型
_bytebyte
_longlong
_shortshort
_intint
_integerint
_doubledouble
_floatfloat
_booleanboolean
stringString
byteByte
longLong
shortShort
intInteger
integerInteger
doubleDouble
floatFloat
booleanBoolean
dateDate
decimalBigDecimal
bigdecimalBigDecimal

类型处理器typeHandlers

类型处理器用于java和jdbc类型的映射。
mybatis支持的类型处理器已经满足日常需要,一般不需要再自定义。
mybatis支持的类型处理器

类型处理器java类型jdbc类型
BooleanTypeHandlerBoolean,boolean任何兼容的布尔值
ByteTypeHandlerByte,byte任何兼容的数字或字节类型
ShortTypeHandlerShort,short任何兼容的数字或短整型
IntegerTypeHandlerInteger,int任何兼容的数字和整型
LongTypeHandlerLong,long任何兼容的数字或长整型
FloatTypeHandlerFloat,float任何兼容的数字或单精度浮点型
DoubleTypeHandlerDouble,double任何兼容的数字或双精度浮点型
BigDecimalTypeHandlerBigDecimal任何兼容的数字或十进制小数类型
StringTypeHandlerStringCHAR和VARCHAR类型
ClobTypeHandlerStringCLOB和LONGVARCHAR类型
NStringTypeHandlerStringNVARCHAR和NCHAR类型
NClobTypeHandlerStringNCLOB类型
ByteArrayTypeHandlerbyte[]任何兼容的字节流类型
BlobTypeHandlerbyte[]BLOB和LONGVARBINARY类型
DateTypeHandlerDate(java.util)TIMESTAMP类型
DateOnlyTypeHandlerDate(java.util)DATE类型
TimeOnlyTypeHandlerDate(java.util)TIME类型
SqlTimestampTypeHandlerTimestamp(java.sql)TIMESTAMP类型
SqlDateTypeHandlerDate(java.sql)DATE类型
SqlTimeTypeHandlerTime(java.sql)TIME类型
ObjectTypeHandler任意其他或未指定类型
EnumTypeHandlerEnumeration类型VARCHAR-任何兼容的字符串类型,作为代码存储(而不是索引)

映射器mappers

参考代码中注释

Mapper.xml 配置详解

Mapper.xml映射文件中定义了操作数据库的sql,每个sql是一个statement,映射文件是mybatis的核心。

parameterType

  • #{}与${}

占位符#{}可以有效防止sql注入,在使用时不需要关心参数值的类型,mybatis会自动进行java类型和jdbc类型的转换。
占位符#{}可以接收简单类型值或pojo属性值.
如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。

占位符${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换。
占位符${}可以接收简单类型值或pojo属性值。
如果parameterType传输单个简单类型值,${}括号中只能是value。

  • 传递简单类型
  • 传递pojo对象
    mybatis使用ognl表达式解析对象字段的值:#{username}
  • 传递包装对象
    mybatis使用ognl表达式解析对象字段的值:#{user.username}
  • 传递hashmap
    mybatis使用映射解析key对应的值:#{key}

resultType

  • 输出简单类型
    <select id="findUserCount" parameterType="user" resultType="int">
    	select count(1) from user
    </select>
    
    输出简单类型必须查询出来的结果集有一条记录,最终将第一个字段的值转换为输出类型。
  • 输出pojo类
    <select id="findUserById" parameterType="int" resultType="user">
    	select * from user where id = #{id}
    </select>
    
    无论单条记录还是多条记录,都用user。只不过底层根据接口的定义使用selectOne还是selectList。
  • 输出hashmap
    将输出的结果改为hashmap输出类型,将字段和值映射为key和value
  • resultMap

    resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。
    如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。

    <resultMap id="queryUserResultMap" type="user">
    	<!-- <id />属性表示结果集的唯一标识,如果是联合主键,可以有多个id -->
        <id column="id_" property="id"/>
        <!-- <result />属性表示结果集的普通属性 -->
        <!-- column表示查询出来的字段名;property表示对应pojo的属性名称 -->
        <result column="username_" property="username"/>
        <result column="address_" property="address"/>
        <result column="sex_" property="sex"/>
        <result column="birthday_" property="birthday"/>
    </resultMap>
    
    <select id="findUserByIdResultMap" parameterType="int" resultMap="queryUserResultMap">
        SELECT id id_,username username_,birthday birthday_,sex sex_,address address_  FROM USER WHERE id = #{id}
    </select>
    

动态sql

  • if判断
    <select id="findUserList" parameterType="user" resultType="user">
    	select * from user 
    	where 1=1 
    	<if test="id!=null and id!=''">
    	and id=#{id}
    	</if>
    	<if test="username!=null and username!=''">
    	and username like '%${username}%'
    	</if>
    </select>
    
    
  • where
    可以自动处理第一个and
    <select id="findUserList" parameterType="user" resultType="user">
    	select * from user 
    	<where>
    		<if test="id!=null and id!=''">
    			and id=#{id}
    		</if>
    		<if test="username!=null and username!=''">
    			and username like '%${username}%'
    		</if>
    	</where>
    </select>
    
  • foreach
    <select id="selectUserByList" parameterType="java.util.List" resultType="user">
    	select * from user 
    	<where>
    		<!-- 传递的是pojo的list集合 -->
    		<if test="list!=null">
    			<foreach collection="list" item="item" open="and id in(" separator="," close=")">
    			    #{item.id} 
    			</foreach>
    		</if>
    	</where>
    </select>
    
    <select id="selectUserByArray" parameterType="Object[]" resultType="user">
    	select * from user 
    	<where>
    		<!-- 传递的是pojo的array数组 -->
    		<if test="array!=null">
    			<foreach collection="array" index="index" item="item" open="and id in(" separator="," close=")">
    			    #{item.id} 
    			</foreach>
    		</if>
    	</where>
    </select>
    
  • sql片段
<sql id="query_user_where">
    <if test="user != null">
        <if test="user.id != 0">
            and id = #{user.id}
        </if>
        <if test="ids != null and ids.size > 0">
            <foreach collection="ids" item="id" open="and id in (" close=")" separator=",">
                #{id}
            </foreach>
        </if>
    </if>
</sql>

<select id="findUserList" parameterType="queryUserVo" resultType="user">
    SELECT * FROM user
    <where>
      <include refid="query_user_where"/>
    </where>
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值