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

SSM 整合入門實戰:MyBatis 配置、DAO 層實現、單元測試完整流程

     編輯:Java 綜合教學

SSM 整合入門實戰:MyBatis 配置、DAO 層實現、單元測試完整流程

SSM(Spring + Spring MVC + MyBatis)是經典 Java Web 技術棧。本文記錄 MyBatis 核心配置、DAO 接口/實現/映射文件、工具類、單元測試完整代碼,作為整合基礎。

1. 依賴 JAR 包

JAR包列表

核心:mybatis、mybatis-spring、spring-jdbc、spring-tx、mysql-connector-java、junit

2. MyBatis 核心配置 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>
    <package name="cn.happy.entity"/>
  </typeAliases>
  
  <environments default="mysql">
    <environment id="mysql">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/y2162"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  
  <mappers>
    <mapper resource="cn/happy/dao/StudentDAO.xml"/>
  </mappers>
</configuration>

3. 實體類

public class Student {
    private int stuno;
    private String stuname;
    private int stuage;
    private Date studate;
    // getter/setter/toString
}

4. DAO 接口

public interface IStudentDAO {
    int addStu(Student stu) throws IOException;
    int delStu(int id) throws IOException;
    List<Student> findAll() throws IOException;
    List<Student> findStudntByName(String stuname) throws IOException;
}

5. DAO 實現類

public class StudentDAOImpl implements IStudentDAO {
    private SqlSession session;
    
    public StudentDAOImpl() throws IOException {
        session = MybatisUtil.getSession();
    }
    
    public List<Student> findAll() throws IOException {
        List<Student> list = session.selectList("findAll");
        session.close();
        return list;
    }
    
    public int addStu(Student stu) throws IOException {
        int result = session.insert("insertStudent", stu);
        session.commit();
        session.close();
        return result;
    }
    // 其他方法類似...
}

6. 映射文件 StudentDAO.xml

<?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="cn.happy.dao">
  <insert id="insertStudent" parameterType="Student">
    insert into student(stuname, stuage, studate) 
    values(#{stuname}, #{stuage}, #{studate})
    <selectKey keyProperty="stuno" resultType="int">
      select @@identity  <!-- MySQL 自增主鍵回填 -->
    </selectKey>
  </insert>
  
  <delete id="delStudent">
    delete from student where stuno=#{id}
  </delete>
  
  <select id="findAll" resultType="Student">
    select * from student
  </select>
  
  <select id="findStudentByName" resultType="Student">
    select * from student where stuname like '%${value}%'
  </select>
</mapper>

7. MyBatis 工具類

public class MybatisUtil {
    private static String config = "mybatis-config.xml";
    private static Reader reader;
    private static SqlSessionFactory factory;
    
    static {
        try {
            reader = Resources.getResourceAsReader(config);
            factory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static SqlSession getSession() throws IOException {
        return factory.openSession();  // 注意:每次獲取新 Session
    }
}

8. 單元測試

public class MyTest {
    private IStudentDAO dao;
    
    @Before
    public void init() throws IOException {
        dao = new StudentDAOImpl();
    }
    
    @Test
    public void testFindAll() throws IOException {
        List<Student> list = dao.findAll();
        list.forEach(s -> System.out.println(s.getStuname()));
    }
    
    @Test
    public void testAdd() throws IOException {
        Student stu = new Student();
        stu.setStuname("張三");
        stu.setStuage(21);
        stu.setStudate(new Date());
        dao.addStu(stu);
        System.out.println("自增ID回填: " + stu.getStuno());
    }
}

Spring 整合關鍵點(後續擴展)

  • DataSource 配置在 Spring 容器,MyBatis 引用:<property name="dataSource" ref="dataSource"/>
  • SqlSessionFactoryBean 整合:<bean class="org.mybatis.spring.SqlSessionFactoryBean">
  • Mapper 掃描器:<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 自動創建 DAO 代理,無需手寫 DAOImpl
  • 事務管理:@Transactional 註解 + DataSourceTransactionManager

總結

MyBatis 獨立使用核心在於:配置文件→實體→DAO接口→映射XML→SqlSessionFactory→SqlSession→CRUD。Spring 整合後由容器管理生命周期,MapperScannerConfigurer 極大簡化 DAO 開發。

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