本文詳細記錄在 Java + Spring + MySQL 技術棧中,如何從零開始搭建並配置 MyBatis 持久層框架。涵蓋環境準備、數據庫建立、實體類與 Mapper 接口定義、SQL 映射文件編寫、核心配置文件配置以及 Spring 整合測試等完整流程,適合初學者快速上手參考。
MyBatis 是一款優秀的持久層框架,支持自定義 SQL、存儲過程以及高級映射。它消除了大量 JDBC 樣板代碼、手動設置參數和結果集提取的工作。MyBatis 通過簡單的 XML 或註解來配置和映射基本數據類型、Map 接口和 POJO 到數據庫記錄中。與 Hibernate 等「全自動」 ORM 方案不同,MyBatis 屬於「半自動化」 ORM 實現,給開發者保留了對 SQL 的完全控制權。
核心依賴包:
mybatis-3.0.2.jar(核心包)mybatis-spring-1.0.0.jar(Spring 整合包)官方下載地址:Apache iBatis、MyBatis Google Code
pom.xml 中添加所需依賴(Spring、MyBatis、MyBatis-Spring、JUnit 等);web.xml 和 Spring 配置文件;可參考:使用 Eclipse Maven 構建 SpringMVC 項目
建立一個學生選課管理數據庫,包含學生表、班級表、教師表、課程表、學生選課表。邏輯關係:每個學生屬於一個班級;每個班級對應一位班主任;每位教師僅能擔任一個班級的班主任。
/* 建立數據庫 */
CREATE DATABASE STUDENT_MANAGER;
USE STUDENT_MANAGER;
/***** 建立 student 表 *****/
CREATE TABLE STUDENT_TBL (
STUDENT_ID VARCHAR(255) PRIMARY KEY,
STUDENT_NAME VARCHAR(10) NOT NULL,
STUDENT_SEX VARCHAR(10),
STUDENT_BIRTHDAY DATE,
CLASS_ID VARCHAR(255)
);
/* 插入學生數據 */
INSERT INTO STUDENT_TBL (STUDENT_ID, STUDENT_NAME, STUDENT_SEX, STUDENT_BIRTHDAY, CLASS_ID)
VALUES (123456, '某某某', '女', '1980-08-01', 121546);
更多建表 SQL 請下載項目源碼,位於 resource/sql 目錄下。
創建 mysql.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student_manager?user=root&password=limingnihao&useUnicode=true&characterEncoding=UTF-8
StudentEntitypublic class StudentEntity implements Serializable {
private static final long serialVersionUID = 3096154202413606831L;
private ClassEntity classEntity;
private Date studentBirthday;
private String studentID;
private String studentName;
private String studentSex;
// 省略 getter/setter 方法
}
StudentMapperpublic interface StudentMapper {
public StudentEntity getStudent(String studentID);
public StudentEntity getStudentAndClass(String studentID);
public List<StudentEntity> getStudentAll();
public void insertStudent(StudentEntity entity);
public void deleteStudent(StudentEntity entity);
public void updateStudent(StudentEntity entity);
}
StudentMapper.xml使用 resultMap 定義字段與屬性映射,select 標籤編寫查詢語句。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.manager.data.StudentMapper">
<resultMap type="StudentEntity" id="studentResultMap">
<id property="studentID" column="STUDENT_ID"/>
<result property="studentName" column="STUDENT_NAME"/>
<result property="studentSex" column="STUDENT_SEX"/>
<result property="studentBirthday" column="STUDENT_BIRTHDAY"/>
</resultMap>
<!-- 根據 ID 查詢學生 -->
<select id="getStudent" parameterType="String" resultType="StudentEntity" resultMap="studentResultMap">
<![CDATA[
SELECT * from STUDENT_TBL ST WHERE ST.STUDENT_ID = #{studentID}
]]>
</select>
<!-- 查詢學生列表 -->
<select id="getStudentAll" resultType="com.manager.data.model.StudentEntity" resultMap="studentResultMap">
<![CDATA[
SELECT * from STUDENT_TBL
]]>
</select>
</mapper>
mybatis-config.xml在 src/main/resource 下創建,配置類型別名和加載 Mapper 映射文件。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity"/>
</typeAliases>
<mappers>
<mapper resource="com/manager/data/maps/StudentMapper.xml" />
</mappers>
</configuration>
關鍵點:配置 SqlSessionFactoryBean 指定 MyBatis 配置文件位置和數據源;配置 Mapper 接口的實現 Bean,可通過 MapperFactoryBean 或註解掃描方式。
<!-- 導入屬性配置文件 -->
<context:property-placeholder location="classpath:mysql.properties" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Mapper Bean 定義方式一:XML 顯式聲明 -->
<bean id="studentMapper" class="org.mybatis.spring.MapperFactoryBean">
<property name="mapperInterface" value="com.manager.data.StudentMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<!-- 方式二:使用註解掃描 (需在 Mapper 接口上添加 @Repository @Transactional) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="annotationClass" value="org.springframework.stereotype.Repository"/>
<property name="basePackage" value="com.liming.manager"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
@Controller
public class TestController {
@Autowired
private StudentMapper studentMapper;
@RequestMapping(value = "index.do")
public void indexPage() {
StudentEntity entity = studentMapper.getStudent("10000013");
System.out.println("name:" + entity.getStudentName());
}
}
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "test-servlet.xml")
public class StudentMapperTest {
@Autowired
private StudentMapper studentMapper;
@Transactional
public void getStudentTest(){
StudentEntity entity = studentMapper.getStudent("10000013");
System.out.println("" + entity.getStudentID() + entity.getStudentName());
List<StudentEntity> studentList = studentMapper.getStudentAll();
for( StudentEntity entityTemp : studentList){
System.out.println(entityTemp.getStudentName());
}
}
}
configuration 根節點下的主要子標籤結構:
configuration
|--- properties
|--- settings
|--- typeAliases
|--- typeHandlers
|--- objectFactory
|--- plugins
|--- environments
| |--- environment
| | |--- transactionManager
| | |--- dataSource
|--- mappers
可引用外部 .properties 文件,也可在標簽內直接覆蓋屬性值。
<properties resource="mysql.properties">
<property name="jdbc.driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="jdbc.url" value="jdbc:mysql://localhost:3306/student_manager"/>
<property name="username" value="root"/>
<property name="password" value="limingnihao"/>
</properties>
MyBatis 提供大量設置項用於微調運行行為(如緩存、延遲加載、自動映射等),此處略過詳細表格,請參考官方文檔。
為 Java 類型定義簡短別名,減少 XML 配置中的全限定類名編寫。MyBatis 內置了常見類型的別名(如 _int、string、map、list 等)。
負責 Java 類型與 JDBC 類型之間的雙向轉換。內置處理器覆蓋了常見類型(StringTypeHandler、DateTypeHandler、BlobTypeHandler 等)。開發者可實現 TypeHandler 接口自定義處理器,並在配置中註冊。
public class LimingStringTypeHandler implements TypeHandler {
@Override
public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, (String) parameter);
}
@Override
public Object getResult(ResultSet rs, String columnName) throws SQLException {
return rs.getString(columnName);
}
@Override
public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getString(columnIndex);
}
}
配置註冊:
<typeHandlers>
<typeHandler javaType="String" jdbcType="VARCHAR" handler="liming.student.manager.type.LimingStringTypeHandler"/>
</typeHandlers>
MyBatis 每次創建結果對象實例都會使用 ObjectFactory。默認使用無參構造器,可繼承 DefaultObjectFactory 自定義實例化邏輯。
MyBatis 允許攔截映射語句執行的特定點(Executor、ParameterHandler、ResultSetHandler、StatementHandler)。插件實現 Interceptor 接口,屬於底層擴展,使用需謹慎。
支持配置多套數據庫環境(如開發、測試、生產),通過 environment 標籤區分,運行時指定具體環境 ID。
告訴 MyBatis 去哪裡尋找 SQL 映射文件,支持類路徑資源引用或 URL 引用。
<mappers>
<mapper resource="com/manager/data/maps/UserMapper.xml" />
<mapper resource="com/manager/data/maps/StudentMapper.xml" />
<mapper resource="com/manager/data/maps/ClassMapper.xml" />
</mappers>
本教程完整演示了在 Spring 環境下整合 MyBatis 並連接 MySQL 的全過程,從項目搭建、數據庫設計、實體與 Mapper 定義、XML 映射編寫、核心配置到 Spring 整合與測試,並深入解析了 MyBatis 主配置文件的各項功能。掌握這些內容,足以應對絕大多數基於 MyBatis 的持久層開發需求。