首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java + Spring + MySQL 環境下整合 MyBatis 完整教程

     編輯:Java 相關知識

前言

本文詳細記錄在 Java + Spring + MySQL 技術棧中,如何從零開始搭建並配置 MyBatis 持久層框架。涵蓋環境準備、數據庫建立、實體類與 Mapper 接口定義、SQL 映射文件編寫、核心配置文件配置以及 Spring 整合測試等完整流程,適合初學者快速上手參考。

1. MyBatis 簡介與整合準備

1.1 MyBatis 核心特性

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

1.2 搭建 Spring + MyBatis + MySQL 基礎環境

1.2.1 搭建 Spring MVC 基礎項目

  1. 創建 Maven Web 項目;
  2. 引入 Spring 框架及配置文件;
  3. 在 pom.xml 中添加所需依賴(Spring、MyBatis、MyBatis-Spring、JUnit 等);
  4. 修改 web.xml 和 Spring 配置文件;
  5. 添加一個 JSP 頁面及對應的 Controller;
  6. 啟動測試。

可參考:使用 Eclipse Maven 構建 SpringMVC 項目

1.2.2 建立 MySQL 數據庫與表結構

建立一個學生選課管理數據庫,包含學生表、班級表、教師表、課程表、學生選課表。邏輯關係:每個學生屬於一個班級;每個班級對應一位班主任;每位教師僅能擔任一個班級的班主任。

/* 建立數據庫 */
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 目錄下。

1.2.3 配置數據庫連接屬性文件

創建 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

2. 搭建 MyBatis 核心環境

2.1 創建實體類 StudentEntity

public 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 方法
}

2.2 定義數據訪問接口 StudentMapper

public 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);
}

2.3 編寫 SQL 映射文件 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>

2.4 創建 MyBatis 全局配置文件 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>

2.5 修改 Spring 配置文件整合 MyBatis

關鍵點:配置 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>

3. 測試驗證

3.1 Spring MVC Controller 測試

@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());
    }
}

3.2 JUnit 單元測試

@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());
        }
    }
}

4. MyBatis 主配置文件深度解析

configuration 根節點下的主要子標籤結構:

configuration
|--- properties
|--- settings
|--- typeAliases
|--- typeHandlers
|--- objectFactory
|--- plugins
|--- environments
|    |--- environment
|    |    |--- transactionManager
|    |    |--- dataSource
|--- mappers

4.1 properties 屬性配置

可引用外部 .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>

4.2 settings 運行行為設置

MyBatis 提供大量設置項用於微調運行行為(如緩存、延遲加載、自動映射等),此處略過詳細表格,請參考官方文檔。

4.3 typeAliases 類型別名

為 Java 類型定義簡短別名,減少 XML 配置中的全限定類名編寫。MyBatis 內置了常見類型的別名(如 _int、string、map、list 等)。

4.4 typeHandlers 類型處理器

負責 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>

4.5 objectFactory 對象工廠

MyBatis 每次創建結果對象實例都會使用 ObjectFactory。默認使用無參構造器,可繼承 DefaultObjectFactory 自定義實例化邏輯。

4.6 plugins 插件機制

MyBatis 允許攔截映射語句執行的特定點(Executor、ParameterHandler、ResultSetHandler、StatementHandler)。插件實現 Interceptor 接口,屬於底層擴展,使用需謹慎。

4.7 environments 多環境配置

支持配置多套數據庫環境(如開發、測試、生產),通過 environment 標籤區分,運行時指定具體環境 ID。

4.8 mappers 映射器註冊

告訴 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 的持久層開發需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved