以下是一个简化的示例,展示如何使用Spring MVC和MyBatis来创建一个简单的报名系统。
- 创建数据库和表:
CREATE DATABASE `league_db`;
USE `league_db`;
CREATE TABLE `participants` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`email` VARCHAR(100) NOT NULL,
`phone` VARCHAR(20),
PRIMARY KEY (`id`)
);
- 实体类 (
Participant.java
):
public class Participant {
private int id;
private String name;
private String email;
private String phone;
// Getters and setters
}
- Mapper接口 (
ParticipantMapper.java
):
@Mapper
public interface ParticipantMapper {
int insertParticipant(Participant participant);
}
- Mapper XML (
ParticipantMapper.xml
):
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.ParticipantMapper">
<insert id="insertParticipant" parameterType="Participant">
INSERT INTO participants(name, email, phone) VALUES(#{name}, #{email}, #{phone})
</insert>
</mapper>
- 服务类 (
ParticipantService.java
):
@Service
public class ParticipantService {
@Autowired
private ParticipantMapper participantMapper;
public void registerParticipant(Participant participant) {
participantMapper.insertParticipant(participant);
}
}
- 控制器类 (
ParticipantController.java
):
@Controller
@RequestMapping("/participants")
public class ParticipantController {
@Autowired
private ParticipantService participantService;
@PostMapping
public String register(@ModelAttribute Participant participant) {
participantService.registerParticipant(participant);
return "redirect:/success";
}
@GetMapping("/success")
public String success() {
return "success";
}
}
- Spring MVC配置 (
WebConfig.java
):
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example")
public class WebConfig implements WebMvcConfigurer {
// Configuration settings
}
- MyBatis配置 (
MyBatisConfig.java
):
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource