2020-11-16

mybatis

入門

安裝

  • 如果使用 Maven 來構(gòu)建項目,則需將下面的依賴代碼置于 pom.xml 文件中:
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>x.x.x</version>
    </dependency>

從 XML 中構(gòu)建 SqlSessionFactory

  • 每個基于 MyBatis 的應(yīng)用都是以一個 SqlSessionFactory 的實(shí)例為核心的。SqlSessionFactory 的實(shí)例可以通過 SqlSessionFactoryBuilder 獲得。而 SqlSessionFactoryBuilder 則可以從 XML 配置文件或一個預(yù)先配置的 Configuration 實(shí)例來構(gòu)建出 SqlSessionFactory 實(shí)例。

從 SqlSessionFactory 中獲取 SqlSession

  • 使用和指定語句的參數(shù)和返回值相匹配的接口(比如 BlogMapper.class),現(xiàn)在你的代碼不僅更清晰,更加類型安全,還不用擔(dān)心可能出錯的字符串字面值以及強(qiáng)制類型轉(zhuǎn)換。
    例如:
    try (SqlSession session = sqlSessionFactory.openSession()) {
    BlogMapper mapper = session.getMapper(BlogMapper.class);
    Blog blog = mapper.selectBlog(101);
    }

XML 配置

配置

  • MyBatis 的配置文件包含了會深深影響 MyBatis 行為的設(shè)置和屬性信息。 配置文檔的頂層結(jié)構(gòu)如下:

屬性(properties)

  • 這些屬性可以在外部進(jìn)行配置,并可以進(jìn)行動態(tài)替換。你既可以在典型的 Java 屬性文件中配置這些屬性,也可以在 properties 元素的子元素中設(shè)置。例如:
    <properties resource="org/mybatis/example/config.properties">
    <property name="username" value="dev_user"/>
    <property name="password" value="F2Fa3!33TYyg"/>
    </properties>
    設(shè)置好的屬性可以在整個配置文件中用來替換需要動態(tài)配置的屬性值。比如:
    <dataSource type="POOLED">
    <property name="driver" value="{driver}"/> <property name="url" value="{url}"/>
    <property name="username" value="{username}"/> <property name="password" value="{password}"/>
    </dataSource>

設(shè)置(settings)

  • 一個配置完整的 settings 元素的示例如下:
    <settings>
    <setting name="cacheEnabled" value="true"/>
    <setting name="lazyLoadingEnabled" value="true"/>
    <setting name="multipleResultSetsEnabled" value="true"/>
    <setting name="useColumnLabel" value="true"/>
    <setting name="useGeneratedKeys" value="false"/>
    <setting name="autoMappingBehavior" value="PARTIAL"/>
    <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
    <setting name="defaultExecutorType" value="SIMPLE"/>
    <setting name="defaultStatementTimeout" value="25"/>
    <setting name="defaultFetchSize" value="100"/>
    <setting name="safeRowBoundsEnabled" value="false"/>
    <setting name="mapUnderscoreToCamelCase" value="false"/>
    <setting name="localCacheScope" value="SESSION"/>
    <setting name="jdbcTypeForNull" value="OTHER"/>
    <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
    </settings>

對象工廠(objectFactory)

  • 每次 MyBatis 創(chuàng)建結(jié)果對象的新實(shí)例時,它都會使用一個對象工廠(ObjectFactory)實(shí)例來完成實(shí)例化工作。 默認(rèn)的對象工廠需要做的僅僅是實(shí)例化目標(biāo)類,要么通過默認(rèn)無參構(gòu)造方法,要么通過存在的參數(shù)映射來調(diào)用帶有參數(shù)的構(gòu)造方法。 如果想覆蓋對象工廠的默認(rèn)行為,可以通過創(chuàng)建自己的對象工廠來實(shí)現(xiàn)。比如:
    // ExampleObjectFactory.java
    public class ExampleObjectFactory extends DefaultObjectFactory {
    public Object create(Class type) {
    return super.create(type);
    }
    public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) {
    return super.create(type, constructorArgTypes, constructorArgs);
    }
    public void setProperties(Properties properties) {
    super.setProperties(properties);
    }
    public <T> boolean isCollection(Class<T> type) {
    return Collection.class.isAssignableFrom(type);
    }}

    <objectFactory type="org.mybatis.example.ExampleObjectFactory">
    <property name="someProperty" value="100"/>
    </objectFactory>

環(huán)境配置(environments)

  • 不過要記?。罕M管可以配置多個環(huán)境,但每個 SqlSessionFactory 實(shí)例只能選擇一種環(huán)境。
  • 每個數(shù)據(jù)庫對應(yīng)一個 SqlSessionFactory 實(shí)例

事務(wù)管理器(transactionManager)

數(shù)據(jù)源(dataSource)

數(shù)據(jù)庫廠商標(biāo)識(databaseIdProvider)

XML 映射文件

  • 映射器(mappers)

    <mappers>
    <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
    <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
    <mapper resource="org/mybatis/builder/PostMapper.xml"/>
    </mappers>

    <mappers>
    <mapper url="file:///var/mappers/AuthorMapper.xml"/>
    <mapper url="file:///var/mappers/BlogMapper.xml"/>
    <mapper url="file:///var/mappers/PostMapper.xml"/>
    </mappers>

    <mappers>
    <mapper class="org.mybatis.builder.AuthorMapper"/>
    <mapper class="org.mybatis.builder.BlogMapper"/>
    <mapper class="org.mybatis.builder.PostMapper"/>
    </mappers>

    <mappers>
    <package name="org.mybatis.builder"/>
    </mappers>

XML 映射文件

1.select

  • <select id="selectPerson" parameterType="int" resultType="hashmap">
    SELECT * FROM PERSON WHERE ID = #{id}
    </select>
  1. insert, update 和 delete
  • 下面是 insert,update 和 delete 語句的示例:
    <insert id="insertAuthor">
    insert into Author (id,username,password,email,bio)
    values (#{id},#{username},#{password},#{email},#{bio})
    </insert>
    <update id="updateAuthor">
    update Author set
    username = #{username},
    password = #{password},
    email = #{email},
    bio = #{bio}
    where id = #{id}
    </update>
    <delete id="deleteAuthor">
    delete from Author where id = #{id}
    </delete>
  1. sql
    這個元素可以用來定義可重用的 SQL 代碼片段,以便在其它語句中使用。 參數(shù)可以靜態(tài)地(在加載的時候)確定下來,并且可以在不同的 include 元素中定義不同的參數(shù)值。比如:
    <sql id="userColumns"> {alias}.id,{alias}.username,{alias}.password </sql> 這個 SQL 片段可以在其它語句中使用,例如: <select id="selectUsers" resultType="map"> select <include refid="userColumns"><property name="alias" value="t1"/></include>, <include refid="userColumns"><property name="alias" value="t2"/></include> from some_table t1 cross join some_table t2 </select> 也可以在 include 元素的 refid 屬性或內(nèi)部語句中使用屬性值,例如: <sql id="sometable">{prefix}Table
    </sql>
    <sql id="someinclude">
    from
    <include refid="${include_target}"/>
    </sql>
    <select id="select" resultType="map">
    select
    field1, field2, field3
    <include refid="someinclude">
    <property name="prefix" value="Some"/>
    <property name="include_target" value="sometable"/>
    </include>
    </select>
  2. 之前見到的所有語句都使用了簡單的參數(shù)形式。但實(shí)際上,參數(shù)是 MyBatis 非常強(qiáng)大的元素。對于大多數(shù)簡單的使用場景,你都不需要使用復(fù)雜的參數(shù),比如:
    <select id="selectUsers" resultType="User">
    select id, username, password
    from users
    where id = #{id}
    </select>
    上面的這個示例說明了一個非常簡單的命名參數(shù)映射。鑒于參數(shù)類型(parameterType)會被自動設(shè)置為 int,這個參數(shù)可以隨意命名。原始類型或簡單數(shù)據(jù)類型(比如 Integer 和 String)因?yàn)闆]有其它屬性,會用它們的值來作為參數(shù)。 然而,如果傳入一個復(fù)雜的對象,行為就會有點(diǎn)不一樣了。比如:
    <insert id="insertUser" parameterType="User">
    insert into users (id, username, password)
    values (#{id}, #{username}, #{password})
    </insert>
  3. 結(jié)果映射
  4. 自動映射

動態(tài) SQL

  • if
  1. <select id="findActiveBlogWithTitleLike"
    resultType="Blog">
    SELECT * FROM BLOG
    WHERE state = ‘ACTIVE’
    <if test="title != null">
    AND title like #{title}
    </if>
    </select>
  2. <select id="findActiveBlogLike"
    resultType="Blog">
    SELECT * FROM BLOG WHERE state = ‘ACTIVE’
    <if test="title != null">
    AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
    AND author_name like #{author.name}
    </if>
    </select>
  • choose (when, otherwise)
    <select id="findActiveBlogLike"
    resultType="Blog">
    SELECT * FROM BLOG WHERE state = ‘ACTIVE’
    <choose>
    <when test="title != null">
    AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
    AND author_name like #{author.name}
    </when>
    <otherwise>
    AND featured = 1
    </otherwise>
    </choose>
    </select>
  • trim (where, set)
    <select id="findActiveBlogLike"
    resultType="Blog">
    SELECT * FROM BLOG
    <where>
    <if test="state != null">
    state = #{state}
    </if>
    <if test="title != null">
    AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
    AND author_name like #{author.name}
    </if>
    </where>
    </select>
  • foreach
    <select id="selectPostIn" resultType="domain.blog.Post">
    SELECT *
    FROM POST P
    WHERE ID in
    <foreach item="item" index="index" collection="list"
    open="(" separator="," close=")">
    #{item}
    </foreach>
    </select>

Java API

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容