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除了可以自定义别名,也有一些默认支持的别名
默认支持别名

别名 映射的类型
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal

类型处理器typeHandlers

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

类型处理器 java类型 jdbc类型
BooleanTypeHandler Boolean,boolean 任何兼容的布尔值
ByteTypeHandler Byte,byte 任何兼容的数字或字节类型
ShortTypeHandler Short,short 任何兼容的数字或短整型
IntegerTypeHandler Integer,int 任何兼容的数字和整型
LongTypeHandler Long,long 任何兼容的数字或长整型
FloatTypeHandler Float,float 任何兼容的数字或单精度浮点型
DoubleTypeHandler Double,double 任何兼容的数字或双精度浮点型
BigDecimalTypeHandler BigDecimal 任何兼容的数字或十进制小数类型
StringTypeHandler String CHAR和VARCHAR类型
ClobTypeHandler String CLOB和LONGVARCHAR类型
NStringTypeHandler String NVARCHAR和NCHAR类型
NClobTypeHandler String NCLOB类型
ByteArrayTypeHandler byte[] 任何兼容的字节流类型
BlobTypeHandler byte[] BLOB和LONGVARBINARY类型
DateTypeHandler Date(java.util) TIMESTAMP类型
DateOnlyTypeHandler Date(java.util) DATE类型
TimeOnlyTypeHandler Date(java.util) TIME类型
SqlTimestampTypeHandler Timestamp(java.sql) TIMESTAMP类型
SqlDateTypeHandler Date(java.sql) DATE类型
SqlTimeTypeHandler Time(java.sql) TIME类型
ObjectTypeHandler 任意 其他或未指定类型
EnumTypeHandler Enumeration类型 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>
发布了48 篇原创文章 · 获赞 1 · 访问量 1042

猜你喜欢

转载自blog.csdn.net/laonxs/article/details/105152861