天天看點

mybatis配置檔案Mybatis核心配置檔案

Mybatis核心配置檔案

mybatis配置檔案Mybatis核心配置檔案

除了上述基本的配置,還有一些常用的設定。

  1. typeAliases(類型别名)

    用xml設定别名(适用于實體類少的情況)

    <typeAliases>
            <typeAlias type="com.wang.pojo.User" alias="User"/>
    </typeAliases>
               
    用注解在實體類上設定别名(适用于實體類比較多)
    @Alias("user")
    public class User {}
               
  2. typeHandlers(類型處理器)
  3. objectFactory(對象工廠)
  4. plugins(插件)
  5. databaseIdProvider(資料庫廠商辨別)
  6. mappers(映射器)

    **MapperRegistry:**注冊綁定我們的Mapper檔案

    <!--每一個Mapper.XML都需要在Mybatis核心配置檔案中注冊!-->
    
    方式1:通過加載xml資源
    <mappers>
        <mapper resource="com/wang/mapper/UserMapper.xml"/>
    </mappers>
    方式2:通過加載類檔案
    <mappers>
        <mapper class="com.wang.mapper.UserMapper"/>
    </mappers>
    方式3:通過包的方式進行掃描
    <mappers>
        <package name="com.wang.mapper"/>
    </mappers>
               

生命周期和作用域的分析

開始---->SqlSessionFactoryBuilder(一旦建立就不再使用)----->SqlSessionFactory(一旦建立一直存在,類似與資料庫連接配接池)----->SqlSession(連接配接到連接配接池的一個請求,存在方法裡面,用完就關閉,否則占用資源,線程不安全)----->SQL Mapper(每一個Mapper代表每一個業務)----->結束

屬性名和字段不一緻問題:

1.起别名

<select id="getUserById" resultType="com.wang.pojo.User">
    select id,name, pwd as password  from mybatis.user where id = #{id}
</select>
           

2.使用resultMap(結果集映射)

<resultMap id="UserMap" type="user">
    <!--column對應資料庫中的字段,property對應實體類中的屬性-->
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="UserMap">
    select * from mybatis.user where id=#{id}
</select>
nt" resultMap="UserMap">
    select * from mybatis.user where id=#{id}
</select>