① 缓存配置(Cache):cacheEnabled:全局开关:默认是true,若是它配成false,其他各个Mapper XML文件配成支持cache也没用。
sql
② 延迟加载:数据库
lazyLoadingEnabled:true使用延迟加载,false禁用延迟加载,默认为true,当禁用时, 全部关联对象都会即时加载。 缓存
aggressiveLazyLoading:true启用时,当延迟加载开启时访问对象中一个懒对象属性时,将彻底加载这个对象的全部懒对象属性。false,当延迟加载时,按需加载对象属性(即访问对象中一个懒对象属性,不会加载对象中其余的懒对象属性)。默认为true。mybatis
③ multipleResultSetsEnabled:容许和不容许单条语句返回多个数据集(取决于驱动需求)。默认为true。app
④ useColumnLabel:使用列标签代替列名称。不一样的驱动器有不一样的作法。参考一下驱动器文档,或者用这两个不一样的选项进行测试一下。ide
⑤ useGeneratedKeys:容许JDBC生成主键。须要驱动器支持。若是设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然能够执行。测试
⑥ autoMappingBehavior:指定MyBatis 是否而且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射全部复杂的结果。fetch
⑦ defaultExecutorType:配置和设定执行器,SIMPLE执行器执行其它语句。REUSE执行器可能重复使用prepared statements语句,BATCH执行器能够重复执行语句和批量更新。ui
⑧ defaultStatementTimeout:设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时。spa
完整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
MyBatis中在查询进行select映射的时候,返回类型能够用resultType,也能够用resultMap,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,可是resultType跟resultMap不能同时存在。在MyBatis进行查询映射的时候,其实查询出来的每个属性都是放在一个对应的Map里面的,其中键是属性名,值则是其对应的值。当提供的返回类型属性是resultType的时候,MyBatis会将Map里面的键值对取出赋给resultType所指定的对象对应的属性。因此其实MyBatis的每个查询映射的返回类型都是ResultMap,只是当咱们提供的返回类型属性是resultType的时候,MyBatis对自动的给咱们把对应的值赋给resultType所指定对象的属性,而当咱们提供的返回类型是resultMap的时候,由于Map不能很好表示领域模型,咱们就须要本身再进一步的把它转化为对应的对象,这经常在复杂查询中颇有做用。
<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
(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代码:
//根据参数名查询参数ID public 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);
selectKey标签,if标签,if + where的条件判断,if + set的更新语句,if + trim代替where/set标签,trim代替set,choose (when, otherwise),foreach标签。动态SQL语句算是MyBatis最灵活的部分吧,用好了很是方便。
<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>