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

核心:mybatis、mybatis-spring、spring-jdbc、spring-tx、mysql-connector-java、junit
<?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>
public class Student {
private int stuno;
private String stuname;
private int stuage;
private Date studate;
// getter/setter/toString
}
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;
}
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;
}
// 其他方法類似...
}
<?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>
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
}
}
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());
}
}
<property name="dataSource" ref="dataSource"/><bean class="org.mybatis.spring.SqlSessionFactoryBean"><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 自動創建 DAO 代理,無需手寫 DAOImpl@Transactional 註解 + DataSourceTransactionManagerMyBatis 獨立使用核心在於:配置文件→實體→DAO接口→映射XML→SqlSessionFactory→SqlSession→CRUD。Spring 整合後由容器管理生命周期,MapperScannerConfigurer 極大簡化 DAO 開發。