使用 Spring Boot 和 MyBatis 实现投票功能的示例,其中 SQL 语句放在 XML 文件中,并且限制每个 IP 地址每天只能投票 4 次,投完票之后需要看排名。前端将使用 Axios 进行请求。
时间: 2024-09-26 11:06:00 浏览: 70
在一个Spring Boot项目中,结合MyBatis和Axios实现投票功能的步骤如下:
首先,你需要设置Spring Boot项目并添加MyBatis和MySQL数据库依赖。在`pom.xml`文件中添加以下内容:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<!-- Axios for frontend -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>com.github.davidmoten</groupId>
<artifactId>webclient-reactive</artifactId>
<version>0.9.14</version>
</dependency>
</dependencies>
```
接下来,在`application.properties`中配置数据库连接:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/voting_system
spring.datasource.username=root
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
```
创建一个简单的投票实体类`Vote.java`:
```java
@Entity
public class Vote {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String ipAddress;
private LocalDateTime voteDate;
// Getters and setters
}
```
然后在MyBatis的Mapper接口(`VoteMapper.java`)中定义投票相关的SQL(XML文件中):
```xml
<mapper namespace="com.example.vote.VoteMapper">
<!-- 插入投票 -->
<insert id="insertVote" parameterType="com.example.vote.Vote">
INSERT INTO votes (ip_address, vote_date) VALUES (#{ipAddress}, NOW())
ON DUPLICATE KEY UPDATE vote_date=VALUES(vote_date), ip_address=VALUES(ip_address)
</insert>
<!-- 查询IP地址的投票次数 -->
<select id="getVoteCountByIpAddress" resultType="int" parameterType="string">
SELECT COUNT(*) FROM votes WHERE ip_address = #{ipAddress} AND vote_date >= DATE_SUB(NOW(), INTERVAL 1 DAY);
</select>
<!-- 获取投票排名 -->
<select id="getTopVotes" resultType="com.example.vote.Vote" limit="5">
SELECT * FROM votes ORDER BY vote_date DESC;
</select>
</mapper>
```
在Service层(`VoteService.java`)中处理业务逻辑:
```java
@Service
public class VoteService {
@Autowired
private VoteMapper voteMapper;
public void insertVote(String ipAddress) {
if (voteMapper.getVoteCountByIpAddress(ipAddress) <= 4) {
voteMapper.insertVote(new Vote(ipAddress));
} else {
throw new RuntimeException("投票限制已达到");
}
}
public List<Vote> getTopVotes() {
return voteMapper.getTopVotes();
}
}
```
最后,在前端使用Axios发起请求:
```javascript
axios.post('/api/vote', { ipAddress: '用户IP' })
.then(response => {
console.log(response.data); // 票数操作结果
})
.catch(error => {
console.error('投票失败:', error.response.data);
});
```
阅读全文