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

MyBatis 入門與 Spring+MySQL 整合完整教程:XML 配置、Mapper、事務、測試全流程

     編輯:Java 相關知識

MyBatis 是優秀的半自動 ORM 框架,支援自定義 SQL、存儲過程、高級映射。本文從核心概念、JAR 依賴、Spring 整合配置、實體/DAO/Mapper 編寫、事務管理、JUnit/SpringMVC 測試,提供一份可直接落地的完整教程。

一、MyBatis 核心概念

  • 半自動 ORM:開發者編寫 SQL,框架負責參數綁定、結果映射、連接管理。
  • 核心組件:SqlSessionFactory、SqlSession、Mapper 接口、XML 映射文件。
  • 優勢:SQL 可控、性能優化靈活、學習曲線平緩、適合複雜查詢。

二、Maven 依賴


<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.13</version>
</dependency>
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>2.0.7</version>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.33</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>5.3.27</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>5.3.27</version>
</dependency>

三、數據庫準備


CREATE DATABASE student_manager;
USE student_manager;
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 VALUES ('10000013', '張三', '男', '2000-01-01', '121546');

四、配置文件體系

1. jdbc.properties


jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student_manager?useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

2. mybatis-config.xml


<?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>

3. Spring 配置 applicationContext.xml


<beans ...>
  <context:property-placeholder location="classpath:jdbc.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 class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.manager.data"/>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
  </bean>
  <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

五、實體類與 Mapper

StudentEntity.java


public class StudentEntity implements Serializable {
    private String studentID;
    private String studentName;
    private String studentSex;
    private Date studentBirthday;
    private ClassEntity classEntity; // 關聯對象
    // getter/setter 略
}

StudentMapper.java (接口)


public interface StudentMapper {
    StudentEntity getStudent(String studentID);
    StudentEntity getStudentAndClass(String studentID); // 關聯查詢
    List<StudentEntity> getStudentAll();
    void insertStudent(StudentEntity entity);
    void deleteStudent(StudentEntity entity);
    void updateStudent(StudentEntity entity);
}

StudentMapper.xml


<mapper namespace="com.manager.data.StudentMapper">
  <resultMap id="studentResultMap" type="StudentEntity">
    <id property="studentID" column="STUDENT_ID"/>
    <result property="studentName" column="STUDENT_NAME"/>
    <result property="studentSex" column="STUDENT_SEX"/>
    <result property="studentBirthday" column="STUDENT_BIRTHDAY"/>
    <association property="classEntity" javaType="ClassEntity">
      <id property="classId" column="CLASS_ID"/>
      <result property="className" column="CLASS_NAME"/>
    </association>
  </resultMap>

  <select id="getStudent" parameterType="String" resultMap="studentResultMap">
    SELECT * FROM student_tbl WHERE student_id = #{studentID}
  </select>

  <select id="getStudentAll" resultMap="studentResultMap">
    SELECT * FROM student_tbl
  </select>

  <insert id="insertStudent" parameterType="StudentEntity">
    INSERT INTO student_tbl (student_id, student_name, student_sex, student_birthday, class_id)
    VALUES (#{studentID}, #{studentName}, #{studentSex}, #{studentBirthday}, #{classEntity.classId})
  </insert>

  <update id="updateStudent" parameterType="StudentEntity">
    UPDATE student_tbl SET student_name=#{studentName}, student_sex=#{studentSex},
      student_birthday=#{studentBirthday}, class_id=#{classEntity.classId}
    WHERE student_id=#{studentID}
  </update>

  <delete id="deleteStudent" parameterType="StudentEntity">
    DELETE FROM student_tbl WHERE student_id=#{studentID}
  </delete>
</mapper>

六、事務管理

  • 配置 DataSourceTransactionManager + <tx:annotation-driven/>。
  • Service 層方法加 @Transactional,異常回滾。
  • 傳播行為、隔離級別、只讀優化按需配置。

七、測試驗證

JUnit 測試


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class StudentMapperTest {
    @Autowired StudentMapper studentMapper;

    @Test
    @Transactional // 測試回滾
    public void testCRUD() {
        StudentEntity s = studentMapper.getStudent("10000013");
        assertNotNull(s);
        List<StudentEntity> list = studentMapper.getStudentAll();
        assertTrue(list.size() > 0);
    }
}

SpringMVC Controller 測試


@Controller
public class TestController {
    @Autowired StudentMapper studentMapper;

    @RequestMapping("/index.do")
    @ResponseBody
    public String index() {
        StudentEntity s = studentMapper.getStudent("10000013");
        return "name: " + s.getStudentName();
    }
}

MyBatis + Spring 整合核心在於:SqlSessionFactoryBean 綁定 DataSource、MapperScannerConfigurer 掃描接口生成代理、事務管理器接管事務邊界。掌握 XML 映射細節(resultMap、association、collection),即可高效完成數據訪問層開發。

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