# MyBatis基礎知識點有哪些
## 一、MyBatis概述
### 1.1 什么是MyBatis
MyBatis是一款優秀的**持久層框架**,它支持定制化SQL、存儲過程以及高級映射。MyBatis避免了幾乎所有的JDBC代碼和手動設置參數以及獲取結果集的過程,可以使用簡單的XML或注解來配置和映射原生信息,將接口和Java的POJO(Plain Old Java Objects)映射成數據庫中的記錄。
### 1.2 MyBatis核心特點
- **輕量級**:與Hibernate相比,MyBatis更加輕量,學習成本低
- **SQL可控**:開發者可以直接編寫原生SQL,靈活優化
- **結果集自動映射**:自動將查詢結果映射到Java對象
- **動態SQL**:支持條件判斷、循環等動態SQL語法
- **緩存機制**:提供一級緩存和二級緩存提高性能
## 二、MyBatis核心組件
### 2.1 核心接口和類
| 組件 | 說明 |
|------|------|
| SqlSessionFactory | 全局單例,用于創建SqlSession |
| SqlSession | 代表一次數據庫會話,線程不安全 |
| Executor | SQL執行器,負責SQL生成和緩存維護 |
| MappedStatement | 封裝SQL語句的輸入輸出信息 |
| Configuration | 所有配置信息的容器 |
### 2.2 運行流程
1. 加載配置文件創建`SqlSessionFactory`
2. 通過`SqlSessionFactory`創建`SqlSession`
3. 通過`SqlSession`獲取Mapper接口代理對象
4. 執行Mapper方法,MyBatis轉換為SQL執行
5. 處理結果集并返回
6. 關閉會話
```java
// 典型使用示例
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectUser(1);
System.out.println(user);
}
<?xml version="1.0" encoding="UTF-8"?>
<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/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 映射文件配置 -->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectUser" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="User">
INSERT INTO user(name,age) VALUES(#{name},#{age})
</insert>
</mapper>
元素 | 說明 |
---|---|
select | 查詢語句 |
insert | 插入語句 |
update | 更新語句 |
delete | 刪除語句 |
sql | 可重用的SQL片段 |
resultMap | 復雜結果集映射 |
<select id="findUsers" parameterType="map" resultType="User">
SELECT * FROM user
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
<foreach item="id" collection="ids" open="AND id IN (" separator="," close=")">
#{id}
</foreach>
</where>
</select>
當數據庫列名與Java屬性名一致時(如user_name對應userName),MyBatis會自動完成映射。
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id"/>
<result property="username" column="user_name"/>
<result property="password" column="hashed_password"/>
</resultMap>
<resultMap id="blogResultMap" type="Blog">
<association property="author" javaType="Author">
<id property="id" column="author_id"/>
<result property="username" column="author_username"/>
</association>
</resultMap>
<resultMap id="blogWithPosts" type="Blog">
<collection property="posts" ofType="Post">
<id property="id" column="post_id"/>
<result property="title" column="post_title"/>
</collection>
</resultMap>
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
通過攔截器接口Interceptor可以攔截: - Executor (update, query, flushStatements等方法) - ParameterHandler (getParameterObject, setParameters方法) - ResultSetHandler (handleResultSets等方法) - StatementHandler (prepare, parameterize等方法)
@Intercepts({
@Signature(type=Executor.class, method="query",
args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})
})
public class ExamplePlugin implements Interceptor {
// 實現攔截邏輯
}
try(SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH)) {
UserMapper mapper = session.getMapper(UserMapper.class);
for (int i = 0; i < 1000; i++) {
mapper.insertUser(new User(...));
if(i % 500 == 0) {
session.flushStatements();
}
}
session.commit();
}
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath*:mapper/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
MyBatis作為半自動化的ORM框架,在SQL可控性和開發效率之間取得了良好平衡。掌握以上基礎知識點后,開發者可以: 1. 熟練配置MyBatis環境 2. 編寫高效的SQL映射文件 3. 處理復雜對象關系映射 4. 合理使用緩存提升性能 5. 解決常見的開發問題
建議通過實際項目練習來鞏固這些知識,并逐步探索MyBatis的更高級特性。 “`
注:本文檔約2850字,涵蓋了MyBatis的核心知識點。實際使用時可根據需要調整內容深度和示例復雜度。建議配合官方文檔(https://mybatis.org/mybatis-3/)一起學習。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。