1. 程式人生 > >mybatis01-創建,基本配置,log4j,動態sql,實現

mybatis01-創建,基本配置,log4j,動態sql,實現

本質 占位符 fix rac property 導入 null XML factory

知識點比較瑣碎,一點點的整理起來的。

一.mybatis創建

mybatis是一個ORM框架,為我們操作數據庫提供了很大的方便。

首先,我是給予maven使用的mybatis

1.導入jar包 mybaits的jar包
2.建立數據庫表,是指對應的實體類
3.創建配置文件 設置數據庫的而連接 引入映射配置文件
主配置文件放在src/main/resource
映射配置 配置實體類和數據庫表的映射關系,設置相關的sql語句
一般放在src/main/java
通過java代碼調用

二.關於mapper.xml的配置

1.<mapper namespace="personNamespace">
namespace調用時的映射名。
personNamespace.add 調用add方法

2.可以使用包含報名類名的命名空間
<mapper namespace="com.qfedu.crud.Person">

3查詢要 有resultType查詢結果類型
支持map類型
<select id="findById" parameterType="int" resultType="Person">

</select>

4.查詢別名的時候,結果的字段名和實體類的屬性不一致時,創建映射
<!-- 表和實體類的對象關系 -->
<!-- property 類中的屬性
column 表中的字段或者別名-->
<resultMap type="Person" id="personMap">
<id property="id" column="id"/>
<id property="name" column="uname"/>
<id property="age" column="age"/>
</resultMap>

resultMap 就是id的值

5.#{}和${}區別

#{} 絕大數情況下使用,將其轉為占位符
${} 參數類型就會改為對應的帶有getset的實體類類型
如果是基本類型(比如"int"),直接使用${} 異常,找不到對應的get方法
參數是直接拼接到sql語句中

6.特殊字符處理
xml小於 < 是特殊字符 處理
<![CDATA[帶有<的語句處理]]> 原樣輸出
或者使用 &lt; 使用實體符號
<![CDATA[select * from person where age < 12]]> 或者
select * from person where age <![CDATA[<]] 12

二.mybatis.xml配置

1.

映射的mapper.xml地址
<mappers>
<mapper resource="com/qfedu/crud/PersonMapper.xml" />
</mappers>

2

<typeAliases>
<!-- 定義別名 alisa是別名 type是定義別名的類型 -->
<typeAlias alias="Person" type="com.qfedu.crud.Person"/>
</typeAliases>

三.動態sql基本語法

1.<where>
</where>
相當於sql的where

2.<trim suffixOverrides=",">
去除最後的 ,
</trim>

3.<if test="條件">
</if>

4.修改數據中的<set></set>
相對於sql的set 自動刪除最後的逗號

5.<choose> 相當於 if(){}else if(){}
<when test="條件">

</when>
<otherwise>
</otherwise>
</choose>

6.
mybatis中,針對非基本類型,本質上參數都會轉為map結構
如果傳來的是列表,轉為map結構後,key值是字符串"list"
如果傳來的是數組,轉為map結構後,key值字符串為“array”
<foreach collection="遍歷的集合" item="遍歷的對象的變量名" separator="分隔符" open=" ("close=")" 指定開始和結束的符號 >
</foreach>

三.實現

1.需要獲得factory這個對象,這裏我用靜態方法

static SqlSessionFactory factory = null;
static {
Reader reader = null;
try {
reader = Resources.getResourceAsReader("mybatis.xml");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

factory = new SqlSessionFactoryBuilder().build(reader);

}

2.定義一個接口類,方法的的返回類型,方法名,參數要同mapper.xml下的select等方法一致。

3.在實現類中,調用實現接口方法。

例如:

EmployeeDao dao = session.getMapper(EmployeeDao.class);//EmployeeDao.class反射接口的反射
dao.finByInfo();

4.log4j

log4j需要導入log4j jar包
導入log4j.properties文件

這樣通過log4j查看運行日誌

mybatis01-創建,基本配置,log4j,動態sql,實現