一、全局配置檔案
執行個體:
mybatis_config.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_achang"/>
<property name="username" value="root"/>
<property name="password" value="00000"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="EmployeeDao.xml"/>
</mappers>
</configuration>
1、properties(屬性)
作用:通過properties标簽引入外部内容
properties标簽:和Spring的context:property-placeholder;引用外部配置檔案
resource屬性:從類路徑下引入
url屬性:引用磁盤路徑或網絡路徑
dbconfig.properties:
username=root
password=00000
url=jdbc:mysql://localhost:3306/mybatis_achang
driver=com.mysql.jdbc.Driver
mybatis_config.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>
<properties resource="dbconfig.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--${}取出配置檔案中的值-->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="EmployeeDao.xml"/>
</mappers>
</configuration>
2、settings(設定)
settings是 MyBatis 中極為重要的調整設定,它們會改變 MyBatis 的運作時行為。
**舉例:**mapUnderscoreToCamelCase
資料庫字段名與bean對象屬性對應駝峰原則
資料庫:login_account
javabean:loginAccount
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
3、typeAliases(類型别名)
推薦還是使用全類名!!!
類型别名:為常用的類型起别名
typeAlias屬性:就是為一個javaBean起别名;别名預設就是類名(不區分大小寫),配置檔案中就可以用别名了
alias屬性:指定一個别名
package屬性:批量起别名
name屬性:指定一個包名,預設别名就是類名
@alias()注解:起别名
<typeAliases>
<typeAlias type="com.achang.bean.Employee" alias="emp"/>//起别名
<package name="com.achang.bean"/>//批量起别名
</typeAliases>
下面是一些為常見的 Java 類型内建的類型别名。它們都是不區分大小寫的,注意,為了應對原始類型的命名重複,采取了特殊的命名風格。
4、typeHandlers(類型處理器)
- 無論是 MyBatis 在預處理語句(PreparedStatement)中設定一個參數時,還是從結果集中取出一個值時, 都會用類型處理器将擷取的值以合适的方式轉換成 Java 類型。
<typeHandlers>
<!--自定義好的類型處理器就這麼配置上就好-->
<typeHandler handler="自定義類型處理器全類名"
</typeHandlers>
5、plugins(插件)
- 插件是MyBatis提供的一個非常強大的機制,我們可以通過插件來修改MyBatis的一些核心行為。插件通過動态代理機制,可以介入四大對象的任何一個方法的執行。後面會有專門的章節我們來介紹mybatis運作原理以及插件
•Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
•ParameterHandler (getParameterObject, setParameters)
•ResultSetHandler (handleResultSets, handleOutputParameters)
StatementHandler (prepare, parameterize, batch, update, query)
6、environments(環境)
default屬性:預設使用哪個環境;填寫某個environment标簽的id
environment标簽:配置一個具體的環境;每一個環境都需要一個事務管理器和資料源
id屬性:目前環境的唯一辨別
transactionManager标簽:事務管理器
後來資料源、事務控制管理都Spring來做;
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--${}取出配置檔案中的值-->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
7、databaseIdProvider(資料庫廠商辨別)
作用:
mybatis用來考慮資料庫移植性的-
name屬性:資料庫廠商辨別
value屬性:給資料庫廠商辨別起别名
MYSQL、Oracle、SQL Server;
mybatis_config.xml
<databaseIdProvider type="DB_VENDOR">
<property name="MYSQL" value="mysql"/>
<property name="SQL Server" value="sqlserver"/>
<property name="Oracle" value="oracle"/>
</databaseIdProvider>
EmployeeDao.xml
databaseId屬性:選擇資料庫廠商别名
<!--能精确比對就精确比對,不能就模糊比對-->
<select id="getEmpById" resultType="com.achang.bean.Employee">
select * from t_employee where id = #{id}
</select>
<select id="getEmpById" resultType="com.achang.bean.Employee" databaseId="mysql">
select * from t_employee where id = #{id}
</select>
<select id="getEmpById" resultType="com.achang.bean.Employee" databaseId="oracle">
select * from t_employee where id = #{id}
</select>
8.mappers(映射器)
<!-- class屬性:引用接口全類名
可以将xml和dao接口放在同一個檔案目錄下,并檔案名和接口名相同
resource屬性:在類路徑下找sql映射檔案
url屬性:從磁盤和網絡路徑引用sql映射檔案
配合使用:重要的dao寫配置;簡單的用頭注解搞定
package标簽:批量注冊;要求xml和dao類接口在同一個檔案夾下且名字相同(可以使用設定資源檔案)
name屬性:dao所在的包名
-->
EmployeeAnnotationDao:在dao接口頭注解上寫對應的sql語句
public interface EmployeeAnnotationDao {
@Select("select * from t_employee where id = #{id}")
public Employee getEmpById(Integer id);
@Update("update t_employee set empname = #{empName},gender = #{gender},email = #{email} where id = #{id}\n")
public int updateEmp(Employee employee);
@Delete("delete from t_employee where id = #{id}")
public boolean deleteEmpById(Integer id);
@Insert("insert into t_employee(empname,gender,email)" +
"values(#{empName},#{gender},#{email}))")
public int insertEmp(Employee employee);
}
使用class導入接口注解頭sql語句類
<!--寫好的sql映射檔案,需要使用mappers注冊-->
<mappers>
<mapper class="com.achang.dao.EmployeeAnnotationDao"/>
<package name=""/>
</mappers>
測試:
//通過注解導入sql語句;查詢
@Test
public void test5() throws IOException {
SqlSession sqlSession = sqlSessionFactory.openSession();
EmployeeAnnotationDao mapper = sqlSession.getMapper(EmployeeAnnotationDao.class);
System.out.println(mapper.getEmpById(3));
}
二、SQL映射檔案
—cache –命名空間的二級緩存配置
—cache-ref – 其他命名空間緩存配置的引用。
—resultMap – 自定義結果集映射
—parameterMap – 已廢棄!老式風格的參數映射,原本是做複雜參數映射的
—sql –抽取可重用語句塊。
—insert – 映射插入語句
—update – 映射更新語句
—delete – 映射删除語句
—select – 映射查詢語句
1、增删改标簽
—insert – 映射插入語句
—update – 映射更新語句
—delete – 映射删除語句
id要對應實作的方法名
<select id="getEmpById" resultType="com.achang.bean.Employee" >
select * from t_employee where id = #{id}
</select>
資料庫支援主鍵:
dao.xml
</select>
<!--讓MyBatis自動的将自增的id指派給傳入的employee對象的id屬性
useGeneratedKeys屬性:開啟自動指派id功能
keyProperty屬性:将剛才自增的id封裝給那個屬性
-->
<insert id="insertEmp" useGeneratedKeys="true" keyProperty="id">
insert into t_employee(empname,gender,email)values(#{empName},#{gender},#{email})
</insert>
bean對象
public class Employee {
private Integer id;
private String empName;
private Integer gender;
private String email;
private String loginAccount;
}
**資料庫沒有主鍵:**selectKey
通過order屬性設定運作順序,keyProperty屬性來設定查詢後結果指派給javabean的哪個對象
然後通過useGeneratedKeys屬性設定打開擷取主鍵,keyProperty屬性設定javabean的id屬性接收結果值
2、參數(Parameters)傳遞
1、單個參數
基本類型:
取值:#{随便寫}
2、多個參數:
取值:#{參數名}是無效的的
0,1(參數索引)或者param1,param2(第幾個參數paramN)
原因:
隻要傳入多個參數,mybatis會自動的将這些參數封裝到一個map中;封裝時使用的key就是參數的索引和參數的第幾個辨別
@param:為參數指定封裝map時的key;命名參數
我們可以告訴mybatis,封裝參數map的時候别亂來
3、傳入map
封裝多個參數為map,直接傳遞
4、傳入bean
取值:#{bean屬性名}
3、參數處理
#{}和¥{}的差別
•實際上通常被設定的是:
可能為空的列名指定 jdbcType
•#{key}:擷取參數的值,預編譯到SQL中。安全。
•${key}:擷取參數的值,拼接到SQL中。有SQL注入問題。ORDER BY ${name}
4、查詢傳回List
EmployeeDao:
public interface EmployeeDao {
public List<Employee> getAllEmps();
}
dao.xml
<!--resultType:如果傳回的是集合,寫的是集合裡面元素的類型-->
<select id="getAllEmps" resultType="com.achang.bean.Employee">
select * from t_employee
</select>
test
@Test
public void test3(){
SqlSession sqlSession = factory.openSession();
EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
List<Employee> allEmps = mapper.getAllEmps();
for (Employee employee:allEmps){
System.out.println(employee);
}
5、查詢傳回Map
1)單條記錄傳回Map
dao
public interface EmployeeDao {
/****
* 列名為Key,值為value
*/
public Map<String,Object> getEmpByIdReturnMap(Integer id);
}
dao.xml
resultType屬性中的map已經被mybatis自動寫入别名為map了
<select id="getEmpByIdReturnMap" resultType="map">
select * from t_employee where id = #{id}
</select>
test
@Test
public void test4(){
SqlSession sqlSession = factory.openSession();
EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
Map<String, Object> empByIdReturnMap = mapper.getEmpByIdReturnMap(3);
System.out.println(empByIdReturnMap);//{empname=歐尼, gender=1, id=3, login_account=b, [email protected]}
}
2)多條記錄傳回Map
通過@MapKey()注解來告訴mybatis資料庫中哪個字段作為key主鍵來,封裝value
dao
public interface EmployeeDao {
//key是記錄的主鍵,value就是記錄封裝好的對象
//@MapKey根據資料庫裡面的哪個字段作為key來查詢封裝value
@MapKey("id")
public Map<Integer,Employee> getEmpsByIdReturnMap();
}
dao.xml
<!--查詢多個的情況下,resultType屬性寫value封裝的元素類型-->
<select id="getEmpsByIdReturnMap" resultType="com.achang.bean.Employee">
select * from t_employee
</select>
test
@Test
public void test5(){
SqlSession sqlSession = factory.openSession();
EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
Map<Integer, Employee> empsByIdReturnMap = mapper.getEmpsByIdReturnMap();
System.out.println(empsByIdReturnMap);
}
6、自定義封裝規則resultMap
reesultMap标簽自定義封裝
type屬性:指定引入哪個javabaen與資料庫封裝對應
id屬性:指定這個自定義封裝的id,便于其他引用
id标簽:指定主鍵
result标簽:指定其他封裝對象
property屬性:指定javabean屬性名
column屬性:指定資料庫字段名
通過resultMap屬性引用那個自定義封裝規則的id