首先,我们需要创建一个学生类(Student)和一个学生表的操作接口(StudentMapper)。

学生类(Student)的代码如下:

public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private String gender;
    // 省略getter和setter方法
}

学生表的操作接口(StudentMapper)的代码如下:

public interface StudentMapper {
    // 添加学生
    void addStudent(Student student);
    
    // 删除学生
    void deleteStudent(Integer id);
    
    // 更新学生
    void updateStudent(Student student);
    
    // 根据ID查询学生
    Student getStudentById(Integer id);
    
    // 查询所有学生
    List<Student> getAllStudents();
}

接下来,我们需要实现这个学生表的操作接口(StudentMapper)。

@Repository
public interface StudentMapper {
    // 添加学生
    void addStudent(Student student);
    
    // 删除学生
    void deleteStudent(Integer id);
    
    // 更新学生
    void updateStudent(Student student);
    
    // 根据ID查询学生
    Student getStudentById(Integer id);
    
    // 查询所有学生
    List<Student> getAllStudents();
}

然后,我们需要在Spring配置文件中配置Mapper扫描和数据源,以及事务管理器。

<!-- 配置Mapper扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.example.mapper"/>
</bean>

<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/test"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
</bean>

<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

最后,我们可以在Service层中调用学生表的操作接口(StudentMapper)进行增删改查操作。

@Service
public class StudentService {
    @Autowired
    private StudentMapper studentMapper;
    
    // 添加学生
    public void addStudent(Student student) {
        studentMapper.addStudent(student);
    }
    
    // 删除学生
    public void deleteStudent(Integer id) {
        studentMapper.deleteStudent(id);
    }
    
    // 更新学生
    public void updateStudent(Student student) {
        studentMapper.updateStudent(student);
    }
    
    // 根据ID查询学生
    public Student getStudentById(Integer id) {
        return studentMapper.getStudentById(id);
    }
    
    // 查询所有学生
    public List<Student> getAllStudents() {
        return studentMapper.getAllStudents();
    }
}

这样,我们就完成了学生表的增删改查操作的SSM代码编写

用ssm代码编写学生表增删改查

原文地址: http://www.cveoy.top/t/topic/iYAB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录