[Java]MyBatis速查筆記

使用示例

1. 配置文件及映射表編寫示例

配置文件及映射表 mybatis.xml

<?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>
    <!-- 1. 加載類路徑下的屬性文件,主要是數據庫的鏈接、密鑰等內容 -->
    <properties resource="db.properties"/>

    <!-- 2.1 設置一個默認的連接環境信息 -->
    <environments default="mybatis_dev">
        <!-- 2.2 某個連接環境的信息,取一個任意唯一的名字(以MySQL爲例) -->
        <environment id="mysql_developer">
            <transactionManager type="jdbc"/> <!-- mybatis使用jdbc事務管理方式 -->
            <!-- 2.3 配置數據源:mybatis使用連接池方式來獲取連接 -->
            <dataSource type="pooled">
                <!-- 2.4 配置與數據庫交互的4個必要屬性 -->
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
    <!-- 其它環境 -->
  </environments>
  
  <!-- 3. 給出映射配置文件-->
  <mappers>
        <mapper resource="./StudentMapper.xml"/>
    <!-- 批量引用,需要PojoA.xml與PojoA.java在同一個目錄中 --><!--
    <package name="examples.pojo"/> -->
    </mappers>
</configuration>

2. 實例類與數據庫表映射文件編寫示例

實例類與數據庫表的映射文件 StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace屬性是名稱空間,必須唯一 -->
<mapper namespace="StudentMapperA">
    <!--    resultMap 標籤:映射實體與表 
              type      屬性:表示實體全路徑名
              id        屬性:爲實體與表的映射取一個任意的唯一的名字 -->
    <resultMap type="example.Student" id="studentMap">
        <!--  id        標籤:映射主鍵屬性
                result    標籤:映射非主鍵屬性
              property  屬性:實體的屬性名
              column    屬性:數據庫表的字段名 -->                         
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="sal" column="sal"/>
    <!-- 關聯屬性,把兩個Map關聯起來 --> <!-- 
    <association property="studentWhatEver" resultMap="StudentMapperB.anotherStudentMap"/> -->
    </resultMap>
  
  <!-- 各種SQL操作語句 
                    id             標籤:語句映射ID,使用"名稱空間.語句映射ID"的方式調用DAO方法/SQL語句
              parameterType  屬性:接受參數的類型
              resultMap      屬性:返回參數的類型一個,<resultMap>:id -->
  <insert id="add" parameterType="example.Student"> <!-- insert("StudentMapperA.add", student)方法-->
        INSERT INTO ZHONGFUCHENG.STUDENTS (ID, NAME, SAL) VALUES (#{id},#{name},#{sal});
    </insert>

  <delete id="delete" parameterType="int"> <!-- delete("StudentMapperA.delete",id)方法 -->
        DELETE FROM STUDENTS WHERE id=#{id};
    </delete>
  
    <update id="update" parameterType="example.Student"> <!-- update("StudentMapperA.update", student)方法 -->
        update students set name=#{name},sal=#{sal} where id=#{id};
    </update>
  
  <select id="findById" parameterType="int" resultMap="studentMap"> <!-- selectOne("StudentMapperA.findById",id) 方法-->
        SELECT * FROM STUDENTS WHERE id = #{id};
    </select>
  <select id="findAll" resultMap="studentMap"> <!-- selectList("StudentMapperA.findAll")方法,返回List<example.Student> -->
        SELECT * FROM STUDENTS;
    </select>
</mapper>
  • resultTyperesultMap 的區別:前者需要數據庫中字段名和Java POJO類中的屬性名一致,且只能一對一;後者根據映射條件即可,可用於一對多即分頁查詢結果返回。

Student 類:

public class Student {  // example.Student
    private Integer id;
    private String name;
    private Double sal;
    public Student() {}

    public Integer getId() {return id;}
    public void setId(Integer id) {this.id = id;}

    public String getName() {return name;}
    public void setName(String name) {this.name = name;}

    public Double getSal() {return sal;}
    public void setSal(Double sal) {this.sal = sal;}
}

3. 動態SQL的編寫示例

<select id="findByCondition" parameterType="map" resultMap="studentMap">
        select * from students
        <where>
            <if test="name!=null">
                and name = #{name}
            </if>
            <if test="sal!=null">
                and sal = #{sal}
            </if>
        </where>
</select>

查詢方法:

Map<String, Object> map = new HashMap()<String, Object>{{
    put("name", name);
    put("sal", sal);
}};
return sqlSession.selectList("StudentID.findByCondition", map);

4. 獲取鏈接和執行語句

public class MybatisUtil {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml"); // 1. 加載位於src/mybatis.xml配置文件
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);  // 2. 構建工廠類
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    private MybatisUtil(){}
    
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = threadLocal.get(); // 從當前線程中獲取SqlSession對象
        if(sqlSession == null){
            sqlSession = sqlSessionFactory.openSession(); // 3. 在SqlSessionFactory非空的情況下,獲取SqlSession對象
            threadLocal.set(sqlSession); // 將SqlSession對象與當前線程綁定在一起
        }
        return sqlSession;
    }
    /**
     * 關閉SqlSession與當前線程分開
     */
    public static void closeSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession != null){
            sqlSession.close(); // 4.關閉SqlSession對象
            threadLocal.remove(); // 5. 分開當前線程與SqlSession對象的關係,目的是讓GC儘早回收
        }
    }   
    
    public static void main(String[] args) {
        Connection conn = MybatisUtil.getSqlSession().getConnection();
        System.out.println(conn!=null?"連接成功":"連接失敗");
        try {
            sqlSession.selectOne("StudentMapperA.findById", 10); //映射文件的命名空間.SQL片段的ID,就可以調用對應的映射文件中的SQL
            sqlSession.commit(); // 手動提交事務
        } catch(Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }
}
  • Mybatis的事務默認是開啓的,需要我們手動去提交事務。

附錄

1 配置文件中的別名

Java中的類型與 parameterType 的映射關係:

Java類型 別名 Java類型 別名
byte _byte Byte byte
long _long Long long
short _short Short short
int _int, _integer Integer int, integer
double _double Double double
float _float Float float
boolean _boolean Boolean boolean
Date date
BigDecimal decimal, bigdecimal

自定義別名:

<typeAliases>
        <!-- 單個別名的定義:type(別名映射的類型) alias(別名)  -->
        <!-- <typeAlias type="example.pojo.PojoA" alias="pojoalias"/> -->
        <!-- 批量別名定義:指定包路徑,自動掃描包下邊的pojo。定義別名,別名默認爲類名(首字母小寫或大寫)-->
        <package name="example.pojo"/>
</typeAliases>

2 延遲加載

設置項 描述 默認值
lazyLoadingEnable 是否全局性的進行懶加載 false
aggressiveLazyLoading 被設置爲true時,可能被懶加載,否則均按需加載 true
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章