mybatis笔记--配置文件和映射文件详解


mybatisd官方文档
代码地址: git@gitee.com:baichen9187/myabtis-demo.git
以下内容来自:手动实例及自己的一些见解和官方文档,和培训班教程集合,

一、Mybatis的全局配置文件

1. SqlMapConfig.xml(名称可变)是mybatis的全局配置文件,配置内容如下:

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

2. properties

	     将数据库连接参数单独配置在db.properties(名称可变)中,放在类路径下。这样只需要在SqlMapConfig.xml中加载db.properties的属性值。这样在SqlMapConfig.xml中就不需要对数据库连接参数硬编码。将数据库连接参数只配置在db.properties中,原因:方便对参数进行统一管理,其它xml可以引用该db.properties

例如:db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root

相应的SqlMapConfig.xml

 <properties resource="db.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <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>

注意: MyBatis 将按照下面的顺序来加载属性:

  1. 首先、在properties标签中指定的属性文件首先被读取。
  2. 其次、会读取properties元素中resource或 url 加载的属性,它会覆盖已读取的同名属性。
  3. 最后、读取parameterType传递的属性,它会覆盖已读取的同名属性。 常用做法: 不要在properties元素体内添加任何属性值,只将属性值定义在外部properties文件中。
    在properties文件中定义属性名要有一定的特殊性,如:XXXXX.XXXXX.XXXX的形式,就像jdbc.driver。这样可以防止和parameterType传递的属性名冲突,从而被覆盖掉。

3. settings

mybatis全局配置参数,全局参数将会影响mybatis的运行行为。比如:开启二级缓存、开启延迟加载。具体可配置情况如下:
在这里插入图片描述

配置示例:

   <settings>
       <setting name="cacheEnabled" value="true"/>
       <setting name="lazyLoadingEnabled" value="true"/>
       <setting name="multipleResultSetsEnabled" value="true"/>
    </settings>
 

4. typeAliases

typeAliases可以用来自定义别名。在mapper.xml中,定义很多的statement,而statement需要parameterType指定输入参数的类型、需要resultType指定输出结果的映射类型。如果在指定类型时输入类型全路径,不方便进行开发,可以针对parameterType或resultType指定的类型定义一些别名,在mapper.xml中通过别名定义,方便开发。
在这里插入图片描述

例如:

 <typeAliases>
        <!-- 单个别名定义 -->
        <typeAlias alias="user" type="com.kang.pojo.User"/>
        <!-- 批量别名定义,扫描整个包下的类,别名为类名(首字母大小写都可以) -->
        <package name="com.kang.pojo"/>
        <package name="其它包"/>
    </typeAliases>
    <select id="findUserById" parameterType="int" resultType="user">
            SELECT * FROM USER WHERE id=#{value}
    </select>
 

5. typeHandlers

mybatis中通过typeHandlers完成jdbc类型和java类型的转换。通常情况下,mybatis提供的类型处理器满足日常需要,不需要自定义。具体可参考Mybatis的官方文档。
在这里插入图片描述
在这里插入图片描述
你可以重写已有的类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。 具体做法为:实现 org.apache.ibatis.type.TypeHandler 接口, 或继承一个很便利的类 org.apache.ibatis.type.BaseTypeHandler, 并且可以(可选地)将它映射到一个 JDBC 类型。比如:

// ExampleTypeHandler.java
@MappedJdbcTypes(JdbcType.VARCHAR) //对应数据库类型
@MappedTypes({String.class})  //java数据类型
//此处如果不用注解指定jdbcType, 那么,就可以在配置文件中通过"jdbcType"属性指定, 同理, javaType 也可通过 @MappedTypes指定
public class ExampleTypeHandler extends BaseTypeHandler<String> {

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
    ps.setString(i, parameter);
  }

  @Override
  public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
    return rs.getString(columnName);
  }

  @Override
  public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    return rs.getString(columnIndex);
  }

  @Override
  public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return cs.getString(columnIndex);
  }
}
<!-- mybatis-config.xml -->
<typeHandlers>
 <typeHandler handler="com.item.ExampleTypeHandler"/>
</typeHandlers>

案例

@Test
    public void findAll()  {
        //6.使用代理对象执行查询所有方法
        List<User> users = userDao.findAll();
        for(User user : users) {
            System.out.println(user);
        }

    }
public interface TypeHandler<T> {

  void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;

  T getResult(ResultSet rs, String columnName) throws SQLException;

  T getResult(ResultSet rs, int columnIndex) throws SQLException;

  T getResult(CallableStatement cs, int columnIndex) throws SQLException;

}
<resultMap id="userMap" type="com.item.domain.User">
        <!-- 主键字段的对应 -->
        <id property="userId" column="id"></id>
        <!--非主键字段的对应-->
        <result property="userName" column="username"></result>
        <result property="userAddress" column="user_address"></result>
        <result property="userSex" column="user_sex"></result>
        <result property="userBirthday" column="user_birthday" typeHandler="com.item.ExampleTypeHandler"></result>
    </resultMap>

可以清楚看到这里的断点被运行了
在这里插入图片描述

使用上述的类型处理器将会覆盖已有的处理 Java String 类型的属性以及 VARCHAR 类型的参数和结果的类型处理器。 要注意 MyBatis 不会通过检测数据库元信息来决定使用哪种类型,所以你必须在参数和结果映射中指明字段是 VARCHAR 类型, 以使其能够绑定到正确的类型处理器上。这是因为 MyBatis 直到语句被执行时才清楚数据类型。

通过类型处理器的泛型,MyBatis 可以得知该类型处理器处理的 Java 类型,不过这种行为可以通过两种方法改变:

在类型处理器的配置元素(typeHandler 元素)上增加一个 javaType 属性(比如:javaType="String");
在类型处理器的类上增加一个 @MappedTypes 注解指定与其关联的 Java 类型列表。 如果在 javaType 属性中也同时指定,则注解上的配置将被忽略。
可以通过两种方式来指定关联的 JDBC 类型:

在类型处理器的配置元素上增加一个 jdbcType 属性(比如:jdbcType=“VARCHAR”);
在类型处理器的类上增加一个 @MappedJdbcTypes 注解指定与其关联的 JDBC 类型列表。 如果在 jdbcType 属性中也同时指定,则注解上的配置将被忽略。
当在 ResultMap 中决定使用哪种类型处理器时,此时 Java 类型是已知的(从结果类型中获得),但是 JDBC 类型是未知的。 因此 Mybatis 使用 javaType=[Java 类型], jdbcType=null 的组合来选择一个类型处理器。 这意味着使用 @MappedJdbcTypes 注解可以限制类型处理器的作用范围,并且可以确保,除非显式地设置,否则类型处理器在 ResultMap 中将不会生效。 如果希望能在 ResultMap 中隐式地使用类型处理器,那么设置 @MappedJdbcTypes 注解的 includeNullJdbcType=true 即可。 然而从 Mybatis 3.4.0 开始,如果某个 Java 类型只有一个注册的类型处理器,即使没有设置 includeNullJdbcType=true,那么这个类型处理器也会是 ResultMap 使用 Java 类型时的默认处理器。

最后,可以让 MyBatis 帮你查找类型处理器:

<!-- mybatis-config.xml -->
<typeHandlers>
  <package name="org.mybatis.example"/>
</typeHandlers>

注意在使用自动发现功能的时候,只能通过注解方式来指定 JDBC 的类型。

你可以创建能够处理多个类的泛型类型处理器。为了使用泛型类型处理器, 需要增加一个接受该类的 class 作为参数的构造器,这样 MyBatis 会在构造一个类型处理器实例的时候传入一个具体的类。

//GenericTypeHandler.java
public class GenericTypeHandler<E extends MyObject> extends BaseTypeHandler<E> {

  private Class<E> type;

  public GenericTypeHandler(Class<E> type) {
    if (type == null) throw new IllegalArgumentException("Type argument cannot be null");
    this.type = type;
  }
  

6. environments

MyBatis 可以配置多种环境。这会帮助你将 SQL 映射应用于多种数据库之中。但是要记得一个很重要的问题:你可以配置多种环境,但每个数据库对应一个 SqlSessionFactory。所以,如果你想连接两个数据库,你需要创建两个 SqlSessionFactory 实例,每个数据库对应一个。而如果是三个数据库,你就需要三个实例,以此类推。
为了明确创建哪种环境,你可以将它作为可选的参数传递给 SqlSessionFactoryBuilder。
可以接受环境配置的两个方法签名是:

SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, environment);
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader,environment,properties);

如果环境被忽略,那么默认环境将会被加载,按照如下方式进行:

SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader);
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader,properties);

源码

在这里插入图片描述

配置示例:

<!-- 配置 mybatis 的环境 -->
    <environments default="mysql1">
    <!-- 配置 mysql 的环境 -->
        <environment id="mysql1">
        <!-- 配置事务的类型 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置连接数据库的信息:用的是数据源(连接池) -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ceshi1?serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>

        <environment id="mysql2">
            <!-- 配置事务的类型 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置连接数据库的信息:用的是数据源(连接池) -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ceshi2?serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>

        <environment id="mysql3">
            <!-- 配置事务的类型 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置连接数据库的信息:用的是数据源(连接池) -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ceshi3?serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

注意:

—默认的环境 ID(比如: default=”mysql1”)。
—每个 environment 元素定义的环境 ID(比如: id=”mysql2”)。
—事务管理器的配置(比如: type=”JDBC”)。 默认的环境和环境 ID 是自我解释的。你可以使用你喜欢的名称来命名,只要确定默认的要匹配其中之一。

7、mappers

Mapper配置的几种方法:

     第一种(常用)
        <mapper resource=" " /> resource指向的是相对于类路径下的目录
         如:<mapper resource="xxx/User.xml" />
     第二种
        <mapper url=" " /> 使用完全限定路径
         如:<mapper url="file:///D:\xxxxx\xxx\User.xml" />
     第三种
        <mapper class=" " /> 使用mapper接口类路径
         如:<mapper class="cn.xx.mapper.UserMapper"/>
注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。
     第四种(推荐)
        <package name=""/> 注册指定包下的所有mapper接口
         如:<package name="cn.xx.mapper"/>
注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。
  使用示例:
    <mappers>
        <mapper resource="xxx/User.xml"/>
        <package name="cn.xx.mapper"/>
    </mappers>

使用 package 注册mapper目录时,可以会出现一些找不到的情况,未知错误

二、Mapper映射文件

  1. Mapper.xml映射文件中定义了操作数据库的sql,每个sql是一个statement,映射文件是mybatis的核心
  2. Mapper映射文件是一个xml格式文件,必须遵循相应的dtd文件规范,如ibatis-3-mapper.dtd
  3. Mapper映射文件是以作为根节点,在根节点中支持9个元素,分别为insert、update、delete、select(增删改查);cache、cache-ref、resultMap、parameterMap、sql

(一)select、parameterMap、resultType、resultMap

 
    
     1、<select
         <!-- (1)id (必须配置)
        id是命名空间中的唯一标识符,可被用来代表这条语句。
        一个命名空间(namespace) 对应一个dao接口,
        这个id也应该对应dao里面的某个方法(相当于方法的实现),因此id 应该与方法名一致  
         -->
     
        id="findUserById"  --- 对应接口中的方法名
     
         <!--(2)parameterType (可选配置, 默认为mybatis自动选择处理)
        将要传入语句的参数的完全限定类名或别名, 如果不配置,mybatis会通过ParameterHandler 根据参数类型默认选择合适的typeHandler进行处理
          parameterType 主要指定参数类型,可以是int, short, long, string等类型,也可以是复杂类型(如对象) 
         -->
        parameterType="int"
     
          <!-- (3)resultType (resultType 与 resultMap 二选一配置)
         resultType用以指定返回类型,指定的类型可以是基本类型,可以是java容器,也可以是javabean 
          -->
        resultType="User"
     
          <!--(4)resultMap (resultType 与 resultMap 二选一配置)
              resultMap用于引用我们通过 resultMap标签定义的映射类型,这也是mybatis组件高级复杂映射的关键 
          -->
        resultMap="userResultMap"
     
          <!--(5)flushCache (可选配置)
         将其设置为 true,任何时候只要语句被调用,都会导致本地缓存和二级缓存都会被清空,默认值:false 
          -->
        flushCache="false"
     
          <!--(6)useCache (可选配置)
         将其设置为 true,将会导致本条语句的结果被二级缓存,默认值:对 select 元素为 true 
          -->
        useCache="true"
     
          <!--(7)timeout (可选配置)
         这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为 unset(依赖驱动)
          -->
        timeout="10000"
     
          <!-- (8)fetchSize (可选配置)
         这是尝试影响驱动程序每次批量返回的结果行数和这个设置值相等。默认值为 unset(依赖驱动)
          -->
        fetchSize="256"
     
          <!--(9)statementType (可选配置)
          STATEMENT,PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED
          -->
     statementType="PREPARED"
     
          <!--(10)resultSetType (可选配置)
         FORWARD_ONLY,SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一个,默认值为 unset (依赖驱动)
          -->
     resultSetType="FORWARD_ONLY"
      >

2、parameterType(输入类型)

通过parameterType指定输入参数的类型,类型可以是简单类型、hashmap、pojo的包装类型。
#{}实现的是向prepareStatement中的预处理语句中设置参数值,sql语句中#{}表示一个占位符即?。
例如:

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

${}和#{}的区别

  • ${}和#{}不同,通过${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换, 可 以 接 收 简 单 类 型 值 或 p o j o 属 性 值 , 如 果 p a r a m e t e r T y p e 传 输 单 个 简 单 类 型 值 , {}可以接收简单类型值或pojo属性值,如 果parameterType传输单个简单类型值,pojoparameterType{}括号中只能是value。使用不 能 防 止 s q l 注 入 , 但 是 有 时 用 {}不能防止sql注入,但是有时用sql{}会非常方便,如下的例子:
<select id="selectUserByName" parameterType="string" resultType="user">
select * from user where username like '%${value}%'
</select>

使用#{}则传入的字符串中必须有%号,而%是人为拼接在参数中,显然有点麻烦,如果采用在 s q l 中 拼 接 为 传 递 参 数 就 方 便 很 多 。 如 果 使 用 {}在sql中拼接为%的方式则在调用mapper接口 传递参数就方便很多。如果使用sql便使{}原始符号则必须人为在传参数中加%。
使用#的如下:

  List<User> list = userMapper.selectUserByName("%管理员%");

(1)parameterType也可以传递pojo对象。Mybatis使用ognl表达式解析对象字段的值,如下例子:

<select id="findUserByUser" parameterType="user" resultType="user">
 select * from user where id=#{id} and username like '%${username}%'
 </select>

上边%${username}%中的username就是user对象中对应的属性名称。
parameterType还可以传递pojo包装对象(也就是将多个对象包装为一个对象)。开发中通过pojo传递查询条件 ,查询条件是综合的查询
条件,不仅包括用户查询条件还包括其它的查询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。
例如下面的包装对象:

 public class QueryVo {
        private User user;
        private UserCustom userCustom;
    }

在映射文件中的使用

 <select id="findUserByUser" parameterType="queryVo" resultType="user">
       select * from user where id=#{user.id} and username like '%${user.username}%'
    </select>

可以看出通过使用类似java中对象访问属性的形式来进行参数传递。

(2)parameterType也可以传递hashmap类型的参数

在xml映射文件中使用形式如下:

 <select id="findUserByHashmap" parameterType="hashmap" resultType="user">
       select * from user where id=#{id} and username like '%${username}%'
      </select>

在代码中的调用形式如下:

 public void testFindUserByHashmap()throws Exception{
           SqlSession session = sqlSessionFactory.openSession();//获取session
           UserMapper userMapper = session.getMapper(UserMapper.class);//获限mapper接口实例
           HashMap<String, Object> map = new HashMap<String, Object>();//构造查询条件Hashmap对象
           map.put("id", 1);
           map.put("username", "管理员");
           List<User>list = userMapper.findUserByHashmap(map);//传递Hashmap对象查询用户列表
           session.close();//关闭session
       }

3、resultType(返回值类型)

  • 使用resultType可以进行输出映射,只有查询出来的列名和pojo中的属性名一致,才可以映射成功。如果查询出来的列名和pojo中的属性名全部不一致,就不会创建pojo对象。但是只要查询出来的列名和pojo中的属性有一个一致,就会创建pojo对象。
  • resultType可以输出简单类型。例如查询用户信息的综合查询列表总数,通过查询总数和上边用户综合查询列表才可以实现分页。
   <!-- 获取用户列表总数 -->
   <select id="findUserCount" parameterType="user" resultType="int">
       select count(*) from user
     </select>

resultType可以输出pojo对象和pojo列表。当使用动态代理时,输出pojo对象和输出pojo列表在xml映射文件中定义的resultType是一样的,而生成的动态代理对象中是根据mapper方法的返回值类型确定是调用selectOne(返回单个对象调用)还是selectList (返回集合对象调用 )。

4、resultMap(输出结果映射)

  • mybatis中可以使用resultMap完成高级输出结果映射。如果查询出来的列名和定义的pojo属性名不一致,就可以通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。然后使用resultMap作为statement的输出映射类型。resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。
 <resultMap id="userMap" type="com.item.domain.User">
        <!-- 主键字段的对应 -->
        <id property="userId" column="id"></id>
        <!--非主键字段的对应-->
        <result property="userName" column="username"></result>
        <result property="userAddress" column="user_address"></result>
        <result property="userSex" column="user_sex"></result>
        <result property="userBirthday" column="user_birthday" typeHandler="com.item.ExampleTypeHandler"></result>
    </resultMap>
<resultMap type="" id="">
         <!-- id:唯一性,注意啦,这个id用于标示这个javabean对象的唯一性, 不一定会是数据库的主键(不要把它理解为数据库对应
             表的主键)
           property:对应javabean的属性名,
           column:对应数据库表的列名
            这样,当javabean的属性与数据库对应表的列名不一致的时候,就能通过指定这个保持正常映射了)
          -->
        <id property="" column=""/>
        
        <!-- result与id相比, 对应普通属性 -->    
        <result property="" column=""/>
        
              <!--
            constructor对应javabean中的构造方法
               -->
        <constructor>
            <!-- idArg 对应构造方法中的id参数 -->
            <idArg column=""/>
            <!-- arg 对应构造方法中的普通参数 -->
            <arg column=""/>
        </constructor>
             <!--
            collection,对应javabean中容器类型, 是实现一对多的关键
            property 为javabean中容器对应字段名
            column 为体现在数据库中列名
            ofType 就是指定javabean中容器指定的类型
             -->
        <collection property="" column="" ofType=""></collection>
        
             <!--
            association 为关联关系,是实现N对一的关键。
            property 为javabean中容器对应字段名
            column 为体现在数据库中列名
            javaType 指定关联的类型
              -->
        <association property="" column="" javaType=""></association>
      </resultMap>
  <select id="findAll" resultMap="userMap">
--         select id as userId,username as userName,address as userAddress,sex as userSex,birthday as userBirthday from user;
        select * from user
    </select>

(二) insert、update、delete

<insert
      <!--(1)id (必须配置)
        id是命名空间中的唯一标识符,可被用来代表这条语句。
        一个命名空间(namespace) 对应一个dao接口,
        这个id也应该对应dao里面的某个方法(相当于方法的实现),因此id 应该与方法名一致 
         -->
      id="addUser"
      
      <!--(2) parameterType (可选配置, 默认为mybatis自动选择处理)
        将要传入语句的参数的完全限定类名或别名, 如果不配置,mybatis会通过ParameterHandler 根据参数类型默认选择合适
           的typeHandler进行处理
        parameterType 主要指定参数类型,可以是int, short, long, string等类型,也可以是复杂类型(如对象) 
         -->
      parameterType="user"
      
      <!--(3)flushCache (可选配置,默认配置为true)
        将其设置为 true,任何时候只要语句被调用,都会导致本地缓存和二级缓存都会被清空,默认值:true(对应插入、更新和
           删除语句) 
          -->
      flushCache="true"
      
      <!--(4)statementType (可选配置,默认配置为PREPARED)
        STATEMENT,PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,
           默认值:PREPARED。 
         -->
      statementType="PREPARED"
      
      <!--(5)keyProperty (可选配置, 默认为unset)
        (仅对 insert 和 update 有用)唯一标记一个属性,MyBatis 会通过 getGeneratedKeys 的返回值或者通过 insert 语句的                  selectKey 子元素设置它的键值,默认:unset。如果希望得到多个生成的列,也可以是逗号分隔的属性名称列表。 
         -->
      keyProperty=""
      
      <!--(6)keyColumn (可选配置)
        (仅对 insert 和 update 有用)通过生成的键值设置表中的列名,这个设置仅在某些数据库(像 PostgreSQL)是必须的,当
           主键列不是表中的第一列的时候需要设置。如果希望得到多个生成的列,也可以是逗号分隔的属性名称列表。 
          -->
      keyColumn=""
      
      <!-- (7)useGeneratedKeys (可选配置, 默认为false)
        (仅对 insert 和 update 有用)这会令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键
           (比如:像 MySQL 和 SQL Server 这样的关系数据库管理系统的自动递增字段),默认值:false。  
          -->
      useGeneratedKeys="false"
      
      <!--(8)timeout  (可选配置, 默认为unset, 依赖驱动)
        这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为 unset(依赖驱动)。 
         -->
      timeout="20"
      >
  
 
 <update
		id="updateUser"
		parameterType="user"
		flushCache="true"
		statementType="PREPARED"
		timeout="20"
         >
 <delete
          id="deleteUser"
          parameterType="user"
          flushCache="true"
          statementType="PREPARED"
          timeout="20"
        >

association实现

association – 一个复杂类型的关联;许多结果将包装成这种类型
嵌套结果映射 – 关联可以是 resultMap 元素,或是对其它结果映射的引用

<!-- 定义封装account和user的resultMap -->
    <resultMap id="accountUserMap" type="com.item.domain.Account">
        <id property="id" column="aid"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!-- 一对一的关系映射:配置封装user的内容-->
        <association property="user" column="uid" javaType="com.item.domain.User">    <!--ofType对应类名-->
            <id property="id" column="id"></id>
            <result column="username" property="username"></result>
            <result column="address" property="address"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
        </association>
    </resultMap>

    <!--assocaition达到延迟加载-->
    <resultMap type="com.item.domain.Account" id="accountMap">
        <id column="aid" property="id"/>
        <result column="uid" property="uid"/>
        <result column="money" property="money"/>
        <!-- 它是用于指定从表方的引用实体属性的 -->
        <association property="user" javaType="com.item.domain.User"
                     select="com.item.dao.IUserDao.findById"
                     column="uid">
        </association>
    </resultMap>

    <select id="findAllas" resultMap="accountMap">
        select * from account
        </select>

    <!-- 查询所有 -->
    <select id="findAll" resultMap="accountUserMap">
        select u.*,a.id as aid,a.uid,a.money from account a , user u where u.id = a.uid;
    </select>

在这里插入图片描述

collection 集合映射

collection – 一个复杂类型的集合
嵌套结果映射 – 集合可以是 resultMap 元素,或是对其它结果映射的引用

public class User implements Serializable {

    private Integer id;
    private String username;
    private String address;
    private String sex;
    private Date birthday;
    private List<Role> roles;
  	。。。
 }
 <!--定义role表的ResultMap-->
    <resultMap id="roleMap" type="com.item.domain.Role">
        <id property="roleId" column="rid"></id>
        <result property="roleName" column="role_name"></result>
        <result property="roleDesc" column="role_desc"></result>
        <collection property="users" ofType="com.item.domain.User">
            <id column="id" property="id"></id>
            <result column="username" property="username"></result>
            <result column="address" property="address"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
        </collection>
    </resultMap>
	 <select id="findAll" resultMap="roleMap">
       select u.*,r.id as rid,r.role_name,r.role_desc from role r
        left outer join user_role ur  on r.id = ur.rid
        left outer join user u on u.id = ur.uid
    </select>

在这里插入图片描述

5. parameterMap

<parameterMap id="puserMap" type="com.item.domain.User">
        <parameter property="userId" resultMap="userMap"/>
        <parameter property="userName" resultMap="userMap"/>
        <parameter property="userAddress" resultMap="userMap"/>
        <parameter property="userSex" resultMap="userMap"/>
        <parameter property="userBirthday" resultMap="userMap"/>
    </parameterMap>
  <insert id="saveUser" parameterMap="puserMap" >
        insert into user(username,user_address,user_sex,user_birthday)value (#{userName},#{userAddress},#{userSex},#{userBirthday})
    </insert>

版权声明:本文为weixin_45904404原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。