StudentMapper
时间: 2025-08-22 10:29:21 浏览: 4
### SSM框架下基于MyBatis的学生信息管理功能中的CRUD操作实现
#### 1. StudentMapper接口设计
在SSM框架中,`StudentMapper` 接口用于定义与数据库交互的方法。这些方法对应于学生信息表的增删改查操作。以下是 `StudentMapper` 接口的完整定义[^1]:
```java
package com.example.mapper;
import com.example.model.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface StudentMapper {
// 查询所有学生
List<Student> selectAll();
// 根据ID查询单个学生
Student selectById(@Param("id") int id);
// 插入新学生
void insert(Student student);
// 更新学生信息
void update(Student student);
// 根据ID删除学生
void deleteById(@Param("id") int id);
}
```
#### 2. XML映射文件实现
`StudentMapper.xml` 文件是 MyBatis 的核心配置文件之一,它定义了 SQL 语句及其与 `StudentMapper` 接口中方法的映射关系。以下是完整的 `StudentMapper.xml` 文件内容[^2]:
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.StudentMapper">
<!-- 查询所有学生 -->
<select id="selectAll" resultType="com.example.model.Student">
SELECT * FROM t_student
</select>
<!-- 根据ID查询单个学生 -->
<select id="selectById" parameterType="int" resultType="com.example.model.Student">
SELECT * FROM t_student WHERE id = #{id}
</select>
<!-- 插入新学生 -->
<insert id="insert" parameterType="com.example.model.Student">
INSERT INTO t_student (name, age, gender, phone) VALUES (#{name}, #{age}, #{gender}, #{phone})
</insert>
<!-- 更新学生信息 -->
<update id="update" parameterType="com.example.model.Student">
UPDATE t_student
SET name = #{name}, age = #{age}, gender = #{gender}, phone = #{phone}
WHERE id = #{id}
</update>
<!-- 根据ID删除学生 -->
<delete id="deleteById" parameterType="int">
DELETE FROM t_student WHERE id = #{id}
</delete>
</mapper>
```
#### 3. CRUD操作的具体实现细节
- **查询所有学生**:通过 `selectAll` 方法从 `t_student` 表中检索所有记录,并将结果映射为 `List<Student>` 类型。
- **根据ID查询单个学生**:通过 `selectById` 方法传入学生ID参数,从 `t_student` 表中检索对应的记录,并将其映射为 `Student` 对象[^3]。
- **插入新学生**:通过 `insert` 方法接收一个 `Student` 对象作为参数,将其字段值插入到 `t_student` 表中。
- **更新学生信息**:通过 `update` 方法接收一个包含更新字段的 `Student` 对象作为参数,仅更新指定ID的记录。
- **删除学生**:通过 `deleteById` 方法接收学生ID参数,从 `t_student` 表中删除对应的记录。
#### 4. 示例代码说明
以下是一个使用 `StudentMapper` 接口进行查询的示例代码片段:
```java
package com.example.service;
import com.example.mapper.StudentMapper;
import com.example.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentService {
@Autowired
private StudentMapper studentMapper;
public List<Student> getAllStudents() {
return studentMapper.selectAll(); // 调用selectAll方法查询所有学生
}
public Student getStudentById(int id) {
return studentMapper.selectById(id); // 调用selectById方法查询单个学生
}
}
```
---
阅读全文
相关推荐




















