Java MyBatis 学生管理系统:实体类、Mapper、Service 和 Controller 实践
Java MyBatis 学生管理系统:实体类、Mapper、Service 和 Controller 实践
本教程将带您一步步构建一个简单的学生管理系统,使用 Java MyBatis 框架。我们将涵盖以下步骤:
- 编写 Student 实体类
public class Student {
private Long id;
private String sname;
private int sage;
private String address;
// 省略 getter 和 setter 方法
}
- 创建 StudentMapper 接口
public interface StudentMapper {
Student findById(Long id);
List<Student> findAll();
List<Student> findBySname(String sname);
}
- 创建并编写 StudentMapper.xml 文件
<mapper namespace="com.example.mapper.StudentMapper">
<select id="findById" resultType="com.example.entity.Student">
select * from student where id = #{id}
</select>
<select id="findAll" resultType="com.example.entity.Student">
select * from student
</select>
<select id="findBySname" resultType="com.example.entity.Student">
select * from student where sname = #{sname}
</select>
</mapper>
- 编写 StudentService 接口和 StudentServiceImpl 实现类
public interface StudentService {
Student getStudent(Long id);
List<Student> getStudents();
List<Student> getStudentsBySname(String sname);
}
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student getStudent(Long id) {
return studentMapper.findById(id);
}
@Override
public List<Student> getStudents() {
return studentMapper.findAll();
}
@Override
public List<Student> getStudentsBySname(String sname) {
return studentMapper.findBySname(sname);
}
}
- 创建并编写 StudentController
@Controller
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("/index")
public ModelAndView allList(HttpSession session) {
ModelAndView mav = new ModelAndView();
User user = (User) session.getAttribute("user");
if (user != null) {
List<Student> students = studentService.getStudents();
mav.addObject("students", students);
mav.setViewName("students");
} else {
mav.setViewName("index");
}
return mav;
}
}
本教程仅提供了一个简单的示例,您可以根据实际需要扩展功能,例如添加学生信息修改、删除等操作。
注意:
- 确保您的项目中已配置 MyBatis 和相关依赖。
- 调整代码中的包名和类名以符合您的项目结构。
- 使用您自己的数据库表名和字段名。
- 完善代码中的逻辑和异常处理。
通过本教程,您应该能够理解使用 Java MyBatis 框架构建一个简单学生管理系统的基本步骤。继续探索 MyBatis 的更多功能,并将其应用于更复杂的项目中。
原文地址: https://www.cveoy.top/t/topic/oIvJ 著作权归作者所有。请勿转载和采集!