package com.example.springboot.controller; import…
- User
package com.example.springboot.controller;
import com.example.springboot.dto.AddWordsRequest; import com.example.springboot.entity.TodayPlan; import com.example.springboot.service.TodayPlanService; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import java.util.List;
@RestController @RequestMapping("/today-plan") public class TodayPlanController {
@Resource private TodayPlanService todayPlanService; @PostMapping("/add") public void addWordsToPlan(@RequestBody AddWordsRequest request) { todayPlanService.addWordsToPlan(request.getUserId(), request.getWordIds()); } @GetMapping("/todaylist") public List<TodayPlan> getTodayPlan(@RequestParam Integer userId) { return todayPlanService.getTodayPlan(userId); } @PostMapping("/delete") public void deleteWordsFromPlan(@RequestBody AddWordsRequest request) { todayPlanService.deletePlansByIds(request.getUserId(), request.getWordIds()); }} package com.example.springboot.service;
import com.example.springboot.entity.TodayPlan; import com.example.springboot.mapper.TodayPlanMapper; import org.springframework.stereotype.Service;
import javax.annotation.Resource; import java.util.List;
@Service public class TodayPlanService {
@Resource private TodayPlanMapper todayPlanMapper; public void addWordsToPlan(Integer userId, List<Integer> wordIds) { todayPlanMapper.batchInsertPlans(userId, wordIds); } public List<TodayPlan> getTodayPlan(Integer userId) { return todayPlanMapper.getTodayPlans(userId); } public List<TodayPlan> exportPlanByIds(Integer userId, List<Integer> ids) { return todayPlanMapper.selectPlansByIds(userId, ids); } public void deletePlansByIds(Integer userId, List<Integer> ids) { todayPlanMapper.deletePlansByIds(userId, ids); }} package com.example.springboot.mapper;
import com.example.springboot.entity.TodayPlan; import org.apache.ibatis.annotations.Param; import java.util.List;
public interface TodayPlanMapper { void batchInsertPlans(@Param("userId") Integer userId, @Param("wordIds") List wordIds); List getTodayPlans(@Param("userId") Integer userId); List exportPlans(@Param("userId") Integer userId);
List<TodayPlan> selectPlansByIds(@Param("userId") Integer userId, @Param("ids") List<Integer> ids); void deletePlansByIds(@Param("userId") Integer userId, @Param("ids") List<Integer> ids);}
<insert id="batchInsertPlans"> INSERT IGNORE INTO user_word_plan (user_id, word_id) VALUES <foreach collection="wordIds" item="wordId" separator=","> (#{userId}, #{wordId}) </foreach> </insert> <select id="getTodayPlans" resultType="com.example.springboot.entity.TodayPlan"> SELECT uwp.*, w.word AS wordText, w.definition AS meaning FROM user_word_plan uwp JOIN words w ON uwp.word_id = w.id WHERE uwp.user_id = #{userId} AND DATE(uwp.added_at) = CURDATE() ORDER BY uwp.added_at DESC </select> <select id="exportPlans" resultType="com.example.springboot.entity.TodayPlan"> SELECT uwp.*, w.word AS wordText, w.definition AS meaning FROM user_word_plan uwp JOIN words w ON uwp.word_id = w.id WHERE uwp.user_id = #{userId} ORDER BY uwp.added_at DESC </select> <select id="selectPlansByIds" resultType="com.example.springboot.entity.TodayPlan"> SELECT uwp.*, w.word AS wordText, w.definition AS meaning FROM user_word_plan uwp JOIN words w ON uwp.word_id = w.id WHERE uwp.user_id = #{userId} AND uwp.id IN <foreach item="id" collection="ids" open="(" separator="," close=")"> #{id} </foreach> </select> <delete id="deletePlansByIds"> DELETE FROM user_word_plan WHERE user_id = #{userId} AND id IN <foreach collection="ids" item="id" open="(" separator="," close=")"> #{id} </foreach> </delete><!-- 操作按钮区域 --> <div class="card" style="margin-bottom: 10px"> <el-button type="primary" :disabled="!selectedIds.size" @click="addSelectedWordsToPlan" style="margin-right: 10px" > 加入背诵计划 </el-button> </div> <!-- 表格区域 --> <div class="card"> <el-table ref="tableRef" :data="tableData" :row-key="row => row.id" stripe border style="width: 100%" @selection-change="handleSelectionChange" :row-class-name="getRowClassName" > <el-table-column type="selection" width="55" :selectable="isSelectable" /> // 单词列 <el-table-column prop="word" label="单词"> <template #default="{ row }"> <el-tooltip v-if="todayPlanWordIds.has(row.id)" content="已在今日计划中" placement="top"> <span>{{ row.word }}</span> </el-tooltip> <span v-else>{{ row.word }}</span> </template> </el-table-column> <el-table-column prop="definition" label="词义" /> <el-table-column prop="customContent" label="例句" /> <el-table-column label="操作" width="100"> <template #default="{ row }"> <el-button size="small" @click="playWord(row.word)">🔊 发音</el-button> </template> </el-table-column> </el-table> <!-- 分页 --> <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="pageSize" :page-sizes="[10, 20, 30, 50]" @size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top: 15px; text-align: right" /> </div> <!-- 今日背诵计划弹窗 --> <el-dialog title="📘 今日背诵计划" v-model="todayPlanDialogVisible" width="60%"> <div style="margin-bottom: 10px; display: flex; justify-content: space-between;"> <div>共 {{ todayPlanTotal }} 个单词</div> </div> <el-table :data="todayPlanWords" @selection-change="handleTodaySelectionChange" stripe border style="width: 100%" > <el-table-column type="selection" width="55" /> <el-table-column prop="wordText" label="单词" /> <el-table-column prop="meaning" label="词义" /> </el-table> <template #footer> <el-button @click="todayPlanDialogVisible = false">关闭</el-button> <el-button type="success" :disabled="!selectedTodayWords.length" @click="exportSelectedTodayWords" > 导出选中单词 </el-button> <el-button type="danger" :disabled="!selectedTodayWords.length" @click="deleteSelectedTodayWords" > 删除选中单词 </el-button> </template> </el-dialog>在用户点击加入背诵计划时,应该检测一下选中的单词是否已存在user_word_plan,long_term_memory里面,如果存在则不能添加
- Assistant
要在“加入背诵计划”时检测选中的单词是否已存在于
user_word_plan(今日背诵计划,表中存的)和long_term_memory(长期记忆,另一个表)中,从而避免重复添加,需要前后端配合,做以下改动:
1. 后端修改
1.1 TodayPlanService 添加校验方法
在
TodayPlanService中,新增一个方法,用于验证用户选中的单词中哪些是不允许再次添加的。@Service public class TodayPlanService { @Resource private TodayPlanMapper todayPlanMapper; @Resource private LongTermMemoryMapper longTermMemoryMapper; // 假设已有此mapper // 之前已有的方法... /** * 返回用户选中的单词中,已经存在于今日计划或长期记忆里的单词id列表 */ public List<Integer> filterExistingWordIds(Integer userId, List<Integer> wordIds) { List<Integer> inTodayPlan = todayPlanMapper.selectExistingWordIds(userId, wordIds); List<Integer> inLongTermMemory = longTermMemoryMapper.selectExistingWordIds(userId, wordIds); // 合并去重 Set<Integer> existing = new HashSet<>(); if (inTodayPlan != null) existing.addAll(inTodayPlan); if (inLongTermMemory != null) existing.addAll(inLongTermMemory); return new ArrayList<>(existing); } }1.2 TodayPlanMapper.xml 中添加查询
<select id="selectExistingWordIds" resultType="int" parameterType="map"> SELECT word_id FROM user_word_plan WHERE user_id = #{userId} AND word_id IN <foreach collection="wordIds" item="wordId" open="(" separator="," close=")"> #{wordId} </foreach> </select>1.3 TodayPlanMapper.java 新增方法
List<Integer> selectExistingWordIds(@Param("userId") Integer userId, @Param("wordIds") List<Integer> wordIds);
1.4 LongTermMemoryMapper 添加类似接口
假设有长期记忆表
long_term_memory,包含(user_id, word_id)字段。<select id="selectExistingWordIds" resultType="int" parameterType="map"> SELECT word_id FROM long_term_memory WHERE user_id = #{userId} AND word_id IN <foreach collection="wordIds" item="wordId" open="(" separator="," close=")"> #{wordId} </foreach> </select>接口类:
public interface LongTermMemoryMapper { List<Integer> selectExistingWordIds(@Param("userId") Integer userId, @Param("wordIds") List<Integer> wordIds); }
1.5 TodayPlanController 修改加入接口,返回不能加入的单词ID或信息给前端
@PostMapping("/add") public ResponseEntity<?> addWordsToPlan(@RequestBody AddWordsRequest request) { Integer userId = request.getUserId(); List<Integer> wordIds = request.getWordIds(); List<Integer> existingWordIds = todayPlanService.filterExistingWordIds(userId, wordIds); List<Integer> toAddWordIds = wordIds.stream() .filter(id -> !existingWordIds.contains(id)) .collect(Collectors.toList()); if (!toAddWordIds.isEmpty()) { todayPlanService.addWordsToPlan(userId, toAddWordIds); } if (existingWordIds.isEmpty()) { return ResponseEntity.ok("添加成功"); } else { return ResponseEntity.status(409).body(Map.of( "message", "部分单词已存在,未重复添加", "existingWordIds", existingWordIds )); } }
2. 前端修改(Vue)
前端发起加入计划请求时,若后台返回 409 状态,代表有重复单词,给用户提示那些单词已存在。
const addSelectedWordsToPlan = async () => { if (!selectedIds.value.size) { ElMessage.warning('请先选择单词') return } try { const wordIds = Array.from(selectedIds.value) await axios.post('http://localhost:8080/today-plan/add', { userId, wordIds }) ElMessage.success('单词已加入背诵计划') if (todayPlanDialogVisible.value) { loadTodayPlan(todayPlanCurrentPage.value) } await loadTodayPlan() fetchWords() } catch (err) { if (err.response && err.response.status === 409) { const existingIds = err.response.data.existingWordIds || [] let existingWords = existingIds.join(', ') ElMessage.warning(`有以下单词已存在计划或长期记忆,未重复添加: ${existingWords}`) // 仍然刷新今日计划,避免界面错误 await loadTodayPlan() fetchWords() } else { ElMessage.error('加入背诵计划失败') } } }你也可以根据返回的
existingWordIds去前端列表中过滤、标记,让用户更直观地看到。
总结
- 后端添加查询单词是否已存在的接口,并在添加时过滤已存在的单词,避免重复添加
- 后端如发现重复,返回 409 状态码和已存在的单词ID列表供前端处理
- 前端根据接口返回的信息,给用户提醒哪些单词已经存在,防止重复添加
- 这样可实现加入背诵计划前,检测
user_word_plan和long_term_memory两个表中对应的单词是否已存在,确保数据准确、无重复
如果你需要,我可以帮你完善
LongTermMemoryMapper对应的代码或者前端对重复单词的展示处理方案。 - User
-- 用户背单词计划表 CREATE TABLE user_word_plan ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, -- 员工ID word_id INT NOT NULL, -- 单词ID added_at DATETIME DEFAULT CURRENT_TIMESTAMP, -- 加入计划时间 status VARCHAR(20) DEFAULT 'pending', -- 例如 pending / reviewed / mastered FOREIGN KEY (user_id) REFERENCES user(id), FOREIGN KEY (word_id) REFERENCES words(id), UNIQUE(user_id, word_id) -- 一个用户不能重复添加同一个单词 );CREATE TABLE long_term_memory ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, word_id INT NOT NULL, review_count INT DEFAULT 0, -- 总复习次数 ease_factor FLOAT DEFAULT 2.5, -- 学习难度因子(如 SuperMemo 算法所需) interval_days INT DEFAULT 0, -- 下次复习间隔(单位:天) next_review_date DATE, -- 下一次复习的目标日期 last_review_date DATE, -- 上一次复习日期 last_score INT DEFAULT NULL, -- 上一次复习的记忆分数(例如 0-5) created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES user(id), FOREIGN KEY (word_id) REFERENCES words(id), UNIQUE(user_id, word_id)); 这是上面两个表
- Assistant
感谢提供表结构,这有助于准确设计查询和接口实现。
根据你给出的两个表结构
user_word_plan和long_term_memory,判断单词已经存在的逻辑可以基于(user_id, word_id)唯一索引进行。
1. 后端MyBatis查询SQL设计
1.1
user_word_plan查询重复单词ID<select id="selectExistingWordIds" resultType="int" parameterType="map"> SELECT word_id FROM user_word_plan WHERE user_id = #{userId} AND word_id IN <foreach collection="wordIds" item="wordId" open="(" separator="," close=")"> #{wordId} </foreach> </select>1.2
long_term_memory查询重复单词ID<select id="selectExistingWordIds" resultType="int" parameterType="map"> SELECT word_id FROM long_term_memory WHERE user_id = #{userId} AND word_id IN <foreach collection="wordIds" item="wordId" open="(" separator="," close=")"> #{wordId} </foreach> </select>
2. Mapper 接口
TodayPlanMapper.java
List<Integer> selectExistingWordIds(@Param("userId") Integer userId, @Param("wordIds") List<Integer> wordIds);LongTermMemoryMapper.java
List<Integer> selectExistingWordIds(@Param("userId") Integer userId, @Param("wordIds") List<Integer> wordIds);
3. Service 层实现示例
@Service public class TodayPlanService { @Resource private TodayPlanMapper todayPlanMapper; @Resource private LongTermMemoryMapper longTermMemoryMapper; public void addWordsToPlan(Integer userId, List<Integer> wordIds) { // 过滤已存在的单词 List<Integer> existingWordIdsInPlan = todayPlanMapper.selectExistingWordIds(userId, wordIds); List<Integer> existingWordIdsInLongTerm = longTermMemoryMapper.selectExistingWordIds(userId, wordIds); // 合并去重 Set<Integer> existingWordIds = new HashSet<>(); if (existingWordIdsInPlan != null) existingWordIds.addAll(existingWordIdsInPlan); if (existingWordIdsInLongTerm != null) existingWordIds.addAll(existingWordIdsInLongTerm); // 过滤待添加的单词ID List<Integer> toAdd = wordIds.stream() .filter(id -> !existingWordIds.contains(id)) .collect(Collectors.toList()); if (!toAdd.isEmpty()) { todayPlanMapper.batchInsertPlans(userId, toAdd); } } public List<Integer> checkWordsExist(Integer userId, List<Integer> wordIds) { List<Integer> existingWordIdsInPlan = todayPlanMapper.selectExistingWordIds(userId, wordIds); List<Integer> existingWordIdsInLongTerm = longTermMemoryMapper.selectExistingWordIds(userId, wordIds); Set<Integer> existingWordIds = new HashSet<>(); if (existingWordIdsInPlan != null) existingWordIds.addAll(existingWordIdsInPlan); if (existingWordIdsInLongTerm != null) existingWordIds.addAll(existingWordIdsInLongTerm); return new ArrayList<>(existingWordIds); } }
4. Controller 层增强,返回存在的单词ID
@PostMapping("/add") public ResponseEntity<?> addWordsToPlan(@RequestBody AddWordsRequest request) { Integer userId = request.getUserId(); List<Integer> wordIds = request.getWordIds(); List<Integer> existingWordIds = todayPlanService.checkWordsExist(userId, wordIds); List<Integer> toAddWordIds = wordIds.stream() .filter(id -> !existingWordIds.contains(id)) .collect(Collectors.toList()); if (!toAddWordIds.isEmpty()) { todayPlanService.addWordsToPlan(userId, toAddWordIds); } if (existingWordIds.isEmpty()) { return ResponseEntity.ok(Map.of("message", "添加成功")); } else { return ResponseEntity.status(409).body(Map.of( "message", "部分单词已存在于背诵计划或长期记忆,未重新添加", "existingWordIds", existingWordIds )); } }
5. 说明
user_word_plan已有唯一(user_id, word_id)约束,防止重复插入。- 本功能在插入前主动查询,提前拒绝重复单词,提高体验并避免错误。
- 如果需要更详细,可在
existingWordIds返回的同时,在Controller层根据词ID查询对应单词详情,前端可提示哪些具体单词已存在。 - 前端在收到 409 状态码后,可以提示用户,并刷新计划列表和单词列表禁用状态。
如果需要,我也可以帮你写好前端弹窗提示处理部分代码。你后续实现时只需调用接口,并按状态码区分处理即可。
如需完整Demo,欢迎继续提问。
- User
package com.example.springboot.controller;
import com.example.springboot.dto.AddWordsRequest; import com.example.springboot.entity.TodayPlan; import com.example.springboot.service.TodayPlanService; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import java.util.List;
@RestController @RequestMapping("/today-plan") public class TodayPlanController {
@Resource private TodayPlanService todayPlanService; @PostMapping("/add") public void addWordsToPlan(@RequestBody AddWordsRequest request) { todayPlanService.addWordsToPlan(request.getUserId(), request.getWordIds()); } @GetMapping("/todaylist") public List<TodayPlan> getTodayPlan(@RequestParam Integer userId) { return todayPlanService.getTodayPlan(userId); } @PostMapping("/delete") public void deleteWordsFromPlan(@RequestBody AddWordsRequest request) { todayPlanService.deletePlansByIds(request.getUserId(), request.getWordIds()); }} package com.example.springboot.service;
import com.example.springboot.entity.TodayPlan; import com.example.springboot.mapper.TodayPlanMapper; import org.springframework.stereotype.Service;
import javax.annotation.Resource; import java.util.List;
@Service public class TodayPlanService {
@Resource private TodayPlanMapper todayPlanMapper; public void addWordsToPlan(Integer userId, List<Integer> wordIds) { todayPlanMapper.batchInsertPlans(userId, wordIds); } public List<TodayPlan> getTodayPlan(Integer userId) { return todayPlanMapper.getTodayPlans(userId); } public List<TodayPlan> exportPlanByIds(Integer userId, List<Integer> ids) { return todayPlanMapper.selectPlansByIds(userId, ids); } public void deletePlansByIds(Integer userId, List<Integer> ids) { todayPlanMapper.deletePlansByIds(userId, ids); }} package com.example.springboot.mapper;
import com.example.springboot.entity.TodayPlan; import org.apache.ibatis.annotations.Param; import java.util.List;
public interface TodayPlanMapper { void batchInsertPlans(@Param("userId") Integer userId, @Param("wordIds") List wordIds); List getTodayPlans(@Param("userId") Integer userId); List exportPlans(@Param("userId") Integer userId);
List<TodayPlan> selectPlansByIds(@Param("userId") Integer userId, @Param("ids") List<Integer> ids); void deletePlansByIds(@Param("userId") Integer userId, @Param("ids") List<Integer> ids);}
<insert id="batchInsertPlans"> INSERT IGNORE INTO user_word_plan (user_id, word_id) VALUES <foreach collection="wordIds" item="wordId" separator=","> (#{userId}, #{wordId}) </foreach> </insert> <select id="getTodayPlans" resultType="com.example.springboot.entity.TodayPlan"> SELECT uwp.*, w.word AS wordText, w.definition AS meaning FROM user_word_plan uwp JOIN words w ON uwp.word_id = w.id WHERE uwp.user_id = #{userId} AND DATE(uwp.added_at) = CURDATE() ORDER BY uwp.added_at DESC </select> <select id="exportPlans" resultType="com.example.springboot.entity.TodayPlan"> SELECT uwp.*, w.word AS wordText, w.definition AS meaning FROM user_word_plan uwp JOIN words w ON uwp.word_id = w.id WHERE uwp.user_id = #{userId} ORDER BY uwp.added_at DESC </select> <select id="selectPlansByIds" resultType="com.example.springboot.entity.TodayPlan"> SELECT uwp.*, w.word AS wordText, w.definition AS meaning FROM user_word_plan uwp JOIN words w ON uwp.word_id = w.id WHERE uwp.user_id = #{userId} AND uwp.id IN <foreach item="id" collection="ids" open="(" separator="," close=")"> #{id} </foreach> </select> <delete id="deletePlansByIds"> DELETE FROM user_word_plan WHERE user_id = #{userId} AND id IN <foreach collection="ids" item="id" open="(" separator="," close=")"> #{id} </foreach> </delete><!-- 操作按钮区域 --> <div class="card" style="margin-bottom: 10px"> <el-button type="primary" :disabled="!selectedIds.size" @click="addSelectedWordsToPlan" style="margin-right: 10px" > 加入背诵计划 </el-button> </div> <!-- 表格区域 --> <div class="card"> <el-table ref="tableRef" :data="tableData" :row-key="row => row.id" stripe border style="width: 100%" @selection-change="handleSelectionChange" :row-class-name="getRowClassName" > <el-table-column type="selection" width="55" :selectable="isSelectable" /> // 单词列 <el-table-column prop="word" label="单词"> <template #default="{ row }"> <el-tooltip v-if="todayPlanWordIds.has(row.id)" content="已在今日计划中" placement="top"> <span>{{ row.word }}</span> </el-tooltip> <span v-else>{{ row.word }}</span> </template> </el-table-column> <el-table-column prop="definition" label="词义" /> <el-table-column prop="customContent" label="例句" /> <el-table-column label="操作" width="100"> <template #default="{ row }"> <el-button size="small" @click="playWord(row.word)">🔊 发音</el-button> </template> </el-table-column> </el-table> <!-- 分页 --> <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="pageSize" :page-sizes="[10, 20, 30, 50]" @size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top: 15px; text-align: right" /> </div> <!-- 今日背诵计划弹窗 --> <el-dialog title="📘 今日背诵计划" v-model="todayPlanDialogVisible" width="60%"> <div style="margin-bottom: 10px; display: flex; justify-content: space-between;"> <div>共 {{ todayPlanTotal }} 个单词</div> </div> <el-table :data="todayPlanWords" @selection-change="handleTodaySelectionChange" stripe border style="width: 100%" > <el-table-column type="selection" width="55" /> <el-table-column prop="wordText" label="单词" /> <el-table-column prop="meaning" label="词义" /> </el-table> <template #footer> <el-button @click="todayPlanDialogVisible = false">关闭</el-button> <el-button type="success" :disabled="!selectedTodayWords.length" @click="exportSelectedTodayWords" > 导出选中单词 </el-button> <el-button type="danger" :disabled="!selectedTodayWords.length" @click="deleteSelectedTodayWords" > 删除选中单词 </el-button> </template> </el-dialog>给我修改后完整可替代的后端代码
- Assistant
好的,结合你提供的代码和需求,我帮你修改整合后端代码,实现“加入背诵计划”时自动检测单词是否已存在于
user_word_plan或long_term_memory表中,避免重复添加,并返回相应信息给前端。
完整修改版 — 后端代码
1. 添加 LongTermMemoryMapper接口和XML
LongTermMemoryMapper.java
package com.example.springboot.mapper; import org.apache.ibatis.annotations.Param; import java.util.List; public interface LongTermMemoryMapper { List<Integer> selectExistingWordIds(@Param("userId") Integer userId, @Param("wordIds") List<Integer> wordIds); }long_term_memory_mapper.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.springboot.mapper.LongTermMemoryMapper"> <select id="selectExistingWordIds" resultType="int" parameterType="map"> SELECT word_id FROM long_term_memory WHERE user_id = #{userId} AND word_id IN <foreach collection="wordIds" item="wordId" open="(" separator="," close=")"> #{wordId} </foreach> </select> </mapper>
2. 修改 TodayPlanMapper.java 增加检查已存在单词的方法
package com.example.springboot.mapper; import com.example.springboot.entity.TodayPlan; import org.apache.ibatis.annotations.Param; import java.util.List; public interface TodayPlanMapper { void batchInsertPlans(@Param("userId") Integer userId, @Param("wordIds") List<Integer> wordIds); List<TodayPlan> getTodayPlans(@Param("userId") Integer userId); List<TodayPlan> exportPlans(@Param("userId") Integer userId); List<TodayPlan> selectPlansByIds(@Param("userId") Integer userId, @Param("ids") List<Integer> ids); void deletePlansByIds(@Param("userId") Integer userId, @Param("ids") List<Integer> ids); // 新增 List<Integer> selectExistingWordIds(@Param("userId") Integer userId, @Param("wordIds") List<Integer> wordIds); }
3. 修改TodayPlanMapper.xml 增加selectExistingWordIds SQL
<select id="selectExistingWordIds" resultType="int" parameterType="map"> SELECT word_id FROM user_word_plan WHERE user_id = #{userId} AND word_id IN <foreach collection="wordIds" item="wordId" open="(" separator="," close=")"> #{wordId} </foreach> </select>
4. TodayPlanService.java 完整代码(含检测逻辑)
package com.example.springboot.service; import com.example.springboot.entity.TodayPlan; import com.example.springboot.mapper.LongTermMemoryMapper; import com.example.springboot.mapper.TodayPlanMapper; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.*; import java.util.stream.Collectors; @Service public class TodayPlanService { @Resource private TodayPlanMapper todayPlanMapper; @Resource private LongTermMemoryMapper longTermMemoryMapper; /** * 添加单词到今日计划,自动过滤已存在于user_word_plan或long_term_memory的单词 * @param userId 用户ID * @param wordIds 待添加单词ID列表 * @return 已存在的单词ID列表 */ public List<Integer> addWordsToPlan(Integer userId, List<Integer> wordIds) { // 查询今天计划和长期记忆中已存在的单词ID List<Integer> existingInPlan = todayPlanMapper.selectExistingWordIds(userId, wordIds); List<Integer> existingInLtm = longTermMemoryMapper.selectExistingWordIds(userId, wordIds); Set<Integer> existingSet = new HashSet<>(); if (existingInPlan != null) existingSet.addAll(existingInPlan); if (existingInLtm != null) existingSet.addAll(existingInLtm); // 过滤要插入的单词ID List<Integer> toAdd = wordIds.stream() .filter(id -> !existingSet.contains(id)) .collect(Collectors.toList()); if (!toAdd.isEmpty()) { todayPlanMapper.batchInsertPlans(userId, toAdd); } // 返回已存在的单词ID给前端做提示 return new ArrayList<>(existingSet); } public List<TodayPlan> getTodayPlan(Integer userId) { return todayPlanMapper.getTodayPlans(userId); } public List<TodayPlan> exportPlanByIds(Integer userId, List<Integer> ids) { return todayPlanMapper.selectPlansByIds(userId, ids); } public void deletePlansByIds(Integer userId, List<Integer> ids) { todayPlanMapper.deletePlansByIds(userId, ids); } }
5. 修改TodayPlanController.java 接口返回结果并处理已存在单词的提醒
package com.example.springboot.controller; import com.example.springboot.dto.AddWordsRequest; import com.example.springboot.entity.TodayPlan; import com.example.springboot.service.TodayPlanService; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; import java.util.Map; @RestController @RequestMapping("/today-plan") public class TodayPlanController { @Resource private TodayPlanService todayPlanService; @PostMapping("/add") public ResponseEntity<?> addWordsToPlan(@RequestBody AddWordsRequest request) { List<Integer> existingWordIds = todayPlanService.addWordsToPlan(request.getUserId(), request.getWordIds()); if (existingWordIds == null || existingWordIds.isEmpty()) { return ResponseEntity.ok(Map.of("message", "单词已全部成功加入背诵计划")); } else { return ResponseEntity.status(409).body(Map.of( "message", "部分单词已存在于今日计划或长期记忆,未重复添加", "existingWordIds", existingWordIds )); } } @GetMapping("/todaylist") public List<TodayPlan> getTodayPlan(@RequestParam Integer userId) { return todayPlanService.getTodayPlan(userId); } @PostMapping("/delete") public void deleteWordsFromPlan(@RequestBody AddWordsRequest request) { todayPlanService.deletePlansByIds(request.getUserId(), request.getWordIds()); } }
6. 总结说明
- 通过两个 Mapper 分别查询
user_word_plan和long_term_memory两张表中的重复单词。 - Service 负责合并结果,过滤重复单词,只插入未存在的。
- Controller 返回
409 Conflict状态码并带上重复单词ID列表,前端根据此判断给提示。 - 数据库的
UNIQUE(user_id, word_id)约束保证不会因并发插入重复数据,安全有保障。 - 你之前的
batchInsertPlans保持用INSERT IGNORE写法安全执行批量插入。
如果你需要,我也可以帮你写前端处理这个新返回响应状态的代码示例。
- 通过两个 Mapper 分别查询
- User
<!-- 操作按钮区域 --> <div class="card" style="margin-bottom: 10px"> <el-button type="primary" :disabled="!selectedIds.size" @click="addSelectedWordsToPlan" style="margin-right: 10px" > 加入背诵计划 </el-button> </div> <!-- 表格区域 --> <div class="card"> <el-table ref="tableRef" :data="tableData" :row-key="row => row.id" stripe border style="width: 100%" @selection-change="handleSelectionChange" :row-class-name="getRowClassName" > <el-table-column type="selection" width="55" :selectable="isSelectable" /> // 单词列 <el-table-column prop="word" label="单词"> <template #default="{ row }"> <el-tooltip v-if="todayPlanWordIds.has(row.id)" content="已在今日计划中" placement="top"> <span>{{ row.word }}</span> </el-tooltip> <span v-else>{{ row.word }}</span> </template> </el-table-column> <el-table-column prop="definition" label="词义" /> <el-table-column prop="customContent" label="例句" /> <el-table-column label="操作" width="100"> <template #default="{ row }"> <el-button size="small" @click="playWord(row.word)">🔊 发音</el-button> </template> </el-table-column> </el-table> <!-- 分页 --> <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="pageSize" :page-sizes="[10, 20, 30, 50]" @size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top: 15px; text-align: right" /> </div> <!-- 今日背诵计划弹窗 --> <el-dialog title="📘 今日背诵计划" v-model="todayPlanDialogVisible" width="60%"> <div style="margin-bottom: 10px; display: flex; justify-content: space-between;"> <div>共 {{ todayPlanTotal }} 个单词</div> </div> <el-table :data="todayPlanWords" @selection-change="handleTodaySelectionChange" stripe border style="width: 100%" > <el-table-column type="selection" width="55" /> <el-table-column prop="wordText" label="单词" /> <el-table-column prop="meaning" label="词义" /> </el-table> <template #footer> <el-button @click="todayPlanDialogVisible = false">关闭</el-button> <el-button type="success" :disabled="!selectedTodayWords.length" @click="exportSelectedTodayWords" > 导出选中单词 </el-button> <el-button type="danger" :disabled="!selectedTodayWords.length" @click="deleteSelectedTodayWords" > 删除选中单词 </el-button> </template> </el-dialog>帮忙更改前端,给我修改后的代码
- Assistant
你后端接口
/today-plan/add已调整为:- 添加重复的单词时返回
409状态,且返回{ message, existingWordIds }。 - 添加成功则返回
200成功信息。
这里帮你调整 前端
addSelectedWordsToPlan函数,实现:- 如果接口返回409,提示重复单词
- 既保持弹出提示,也能刷新今日计划和单词列表状态
- 其余逻辑保持不变
修改后的前端关键代码段
// 加入背诵计划 const addSelectedWordsToPlan = async () => { if (!selectedIds.value.size) { ElMessage.warning('请先选择单词') return } try { const wordIds = Array.from(selectedIds.value) await axios.post('http://localhost:8080/today-plan/add', { userId, wordIds }) ElMessage.success('单词已加入背诵计划') if (todayPlanDialogVisible.value) { loadTodayPlan(todayPlanCurrentPage.value) } // 重新加载已加入计划的 ID,刷新禁选状态 await loadTodayPlan() fetchWords() } catch (err) { if (err.response && err.response.status === 409) { const data = err.response.data || {} const existingIds = data.existingWordIds || [] // 你可以根据已有单词ID在tableData中找到对应的单词, 拼接提示内容 const existingWords = tableData.value .filter(item => existingIds.includes(item.id)) .map(item => item.word) .join(',') ElMessage.warning(`部分单词已存在背诵计划或长期记忆,未重复添加: ${existingWords}`) // 仍然刷新接口,保持界面状态 if (todayPlanDialogVisible.value) { await loadTodayPlan(todayPlanCurrentPage.value) } await loadTodayPlan() fetchWords() } else { ElMessage.error('加入背诵计划失败') } } }
你所有代码中这段替换即可,其他代码保持不变。
相关说明:
- 这里对
409错误进行了专门判断,拿到服务器返回的重复单词ID - 依赖当前单词表的
tableData尝试找到对应单词拼成提示信息 - 提示内容写得清晰些,告诉用户哪些重复了
- 随后刷新今日计划和单词列表,保证UI一致
- 其他异常按你的原始逻辑弹失败提示
如果你需要,我也可以帮你写更完整示例或者其他需求。
- 添加重复的单词时返回
- User
<!-- 左侧:学习单词区域 --> <el-col :span="12" class="left-panel" style="height: 100%;"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;"> <h2>短期记忆区域</h2> <div> <el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button> <el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button> </div> </div> <!-- 待复习单词数量 --> <div class="pending-count" v-if="reviewList.length"> 待复习单词数量: {{ pendingCount }} </div> <!-- 单词卡片 --> <div class="card-container" v-if="reviewList.length"> <div class="card-wrapper"> <div class="card" :class="{ flipped: isFlipped }"> <div class="card-face card-front"> <!-- 正面不显示通过次数,如果需要,类似写这里 --> <h1>{{ currentWord.word }}</h1> <el-button @click.stop="speakWord(currentWord.word)" style="...">🔊 发音</el-button> </div> <div class="card-face card-back" style="position: relative;"> <!-- 通过次数左上角绝对定位 --> <div class="score-badge"> 通过次数: {{ currentWord.score ?? 0 }} </div> <h1 style="margin-top: 40px;">{{ currentWord.word }}</h1> <p><strong>释义:</strong>{{ currentWord.definition }}</p> <el-button @click.stop="speakWord(currentWord.word)" style="...">🔊 发音</el-button> </div> </div> <div class="btn-group"> <el-button type="danger" v-if="!isFlipped" @click="flipCard">忘记</el-button> <el-button type="success" v-if="!isFlipped" @click="flipCard">认识</el-button> <el-button type="danger" v-if="isFlipped" @click="submitReviewResult(false)">忘记</el-button> <el-button type="success" v-if="isFlipped" @click="submitReviewResult(true)">认识</el-button> </div> </div> </div> <!-- 无可复习单词提示 --> <div v-else style="text-align:center; margin-top: 50px; font-size: 20px; color: #999;"> 无可复习单词,复习完成! </div> <!-- 已选单词弹窗 --> <el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px"> <el-table :data="selectedWords" style="width: 100%;" border @selection-change="handleSelectedChange" > <el-table-column type="selection" width="55" /> <el-table-column prop="id" label="ID" width="80" /> <el-table-column prop="word" label="单词" /> <el-table-column prop="definition" label="释义" /> <el-table-column label="操作" width="100"> <template #default="scope"> <el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button> </template> </el-table-column> </el-table> <template #footer> <span class="dialog-footer"> <el-button @click="selectedDialogVisible = false">关闭</el-button> <el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords"> 批量删除({{ selectedToDelete.length }}) </el-button> </span> </template> </el-dialog> </el-col> <!-- 右侧区域 --> <el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;"> <h2>暂未开发</h2> <p>暂未开发</p> </el-col> <!-- 选择待学习单词弹窗 --> <el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px"> <el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange"> <el-table-column type="selection" width="55" /> <el-table-column prop="word" label="单词" /> <el-table-column prop="definition" label="释义" /> </el-table> <template #footer> <span class="dialog-footer"> <el-button @click="dialogVisible = false">取消</el-button> <el-button type="primary" @click="submitSelectedWords">确认选择({{ selectedToAdd.length }})</el-button> </span> </template> </el-dialog>为什么每次导航栏跳转到这个页面都会显示第一轮复习结束,无更多单词
- Assistant
你提供的Vue组件代码结构和逻辑看起来大致没问题,“第一轮复习结束,无更多单词” 的提示是由你
fetchReviewList()方法里面这段触发的:if (reviewList.value.length === 0) { ElMessage.success(`第${round.value}轮复习结束,无更多单词`) return }
导致该提示一直出现的可能原因及排查思路
1. 后端接口
/study/review-list一直返回空数组-
每次调用
fetchReviewList,请求:const res = await axios.get('/study/review-list', { params: { userId: Number(userId), round: round.value } }) -
如果该接口对你传的
round和userId都正确,但一直返回[]空列表:- 说明你当前用户确实没有待复习单词。
- 或者后端业务逻辑可能有问题或数据错乱,比如没有给该用户该轮次的单词,下述可能导致。
2.
round.value初始是 1,但有没有合理初始化?-
代码显示
round是个ref(1),写法正常。 -
但要注意:
-
你在复习全部结束后,
round.value会++增加,如果你路由切换再回来,而round没重置为1,接口可能查询的是一个不存在的轮数。 -
在
onMounted里你的代码是:onMounted(async () => { speechSynthesis.speak(new SpeechSynthesisUtterance(' ')) await fetchPendingCount() await fetchReviewList() })但是没有重置
round.value。
-
-
建议把
round.value = 1放这里,避免多次路由切回来时,round持续累加:onMounted(async () => { round.value = 1 // 重置轮次 speechSynthesis.speak(new SpeechSynthesisUtterance(' ')) await fetchPendingCount() await fetchReviewList() })
3.
userId是否正确传给接口?-
你
userId获取是localStorage.getItem('userId'),返回字符串。 -
你调用接口时一般用了
Number(userId)转数字。 -
如果未登录或本地没存该 key,会导致传入后端空或者 NaN,接口也返回空。
-
建议在调用接口前加日志:
console.log('UserId:', userId, 'Round:', round.value)确认是否有
userId,且与后台期望一致。
4. 后端接口
/study/review-list业务逻辑问题-
如果确定前端没问题,建议查下后端接口的 sql 或业务实现:
- 是否有条件判断导致返回空数组。
- 是否根据
round或其他条件过滤了数据。 - 是否用户没有对应数据。
综合建议和修改示例
修改
onMounted重置 roundonMounted(async () => { round.value = 1 // 增加这一句,重置轮次 speechSynthesis.speak(new SpeechSynthesisUtterance(' ')) await fetchPendingCount() await fetchReviewList() })
增加打印调试
userId和round在
fetchReviewList开头:async function fetchReviewList() { const userId = localStorage.getItem('userId') console.log('fetchReviewList userId:', userId, 'round:', round.value) if (!userId) return ElMessage.warning('请先登录或设置 userId') try { const res = await axios.get('/study/review-list', { params: { userId: Number(userId), round: round.value } }) // ...
确认后端接口是否有数据或返回格式正确
-
使用 Postman 或curl,测试下接口:
GET http://localhost:8080/study/review-list?userId=你的用户id&round=1 -
查看返回数据,确保有数据且非空数组。
额外检查
- 是否路由跳转和页面切换时组件销毁和挂载正确,导致数据未刷新。
- 如果用keep-alive缓存组件,保证每次进入时重置了
round和初始化数据。
总结
你页面提示“第1轮复习结束,无更多单词”是因为数据接口返回空数组。
- 优先确认后端数据是否存在。
- 前端务必保证
round重置正常,userId有效。 - 增加调试打印排查请求参数和接口响应。
- 修正
onMounted里加round.value=1防止轮次累加错误。
如果需要,我可以帮你写后端接口的示例SQL逻辑或辅助调试代码。需要请告诉我!
-
- User
为什么要显示第几轮复习结束,无更多单词,用户无需知道多少轮结束
- Assistant
这是人为设计上的一个提示,目的是告诉用户当前复习阶段已经完成了。但确实,大多数情况下普通用户并不关心「第几轮」的数字,只要知道“复习结束”就好。
为什么显示轮次信息?
- 复习流程里“轮次”用于内部流程控制和复习算法,比如:
- 第一轮做完开始第二轮。
- 多轮复习不断循环强化记忆。
- 有时给用户显示「第n轮复习结束」是一种进度反馈,增强用户感。
- 对某些教育产品,用户可能关注自己复习了几轮。
你可以考虑:
- 去掉具体轮次,只显示“复习结束,无更多单词”即可,更简洁易懂。
- 设计用户更直观的进度或复习状态提示,比如“当前复习已全部完成,恭喜!”,或者“暂无待复习单词”等。
简单修改示例
把这一段:
if (reviewList.value.length === 0) { ElMessage.success(`第${round.value}轮复习结束,无更多单词`) return }改成:
if (reviewList.value.length === 0) { ElMessage.success(`复习结束,无更多单词`) return }
更好一点的提示 UX 建议
- 你甚至可以不弹消息,而是页面上显示“无复习单词”板块(你已有了),减少干扰。
- 如果想保留提示,建个有关闭按钮的浅色的提示条,容易被用户注意且不突兀。
总结
- 显示第几轮复习结束是设计者给的一个带进度感的提示,不是必须。
- 如果用户实际不需要,可删掉或换成简单提示。
- 用户体验上,尽量提示要简洁、易懂、避免多余数字干扰。
需要的话我可以帮你写「无复习单词时不弹消息,仅显示页面空状态」的示例代码。
- 复习流程里“轮次”用于内部流程控制和复习算法,比如:
- User
<!-- 左侧:学习单词区域 --> <el-col :span="12" class="left-panel" style="height: 100%;"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;"> <h2>短期记忆区域</h2> <div> <el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button> <el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button> </div> </div> <!-- 待复习单词数量 --> <div class="pending-count" v-if="reviewList.length"> 待复习单词数量: {{ pendingCount }} </div> <!-- 单词卡片 --> <div class="card-container" v-if="reviewList.length"> <div class="card-wrapper"> <div class="card" :class="{ flipped: isFlipped }"> <div class="card-face card-front"> <!-- 正面不显示通过次数,如果需要,类似写这里 --> <h1>{{ currentWord.word }}</h1> <el-button @click.stop="speakWord(currentWord.word)" style="...">🔊 发音</el-button> </div> <div class="card-face card-back" style="position: relative;"> <!-- 通过次数左上角绝对定位 --> <div class="score-badge"> 通过次数: {{ currentWord.score ?? 0 }} </div> <h1 style="margin-top: 40px;">{{ currentWord.word }}</h1> <p><strong>释义:</strong>{{ currentWord.definition }}</p> <el-button @click.stop="speakWord(currentWord.word)" style="...">🔊 发音</el-button> </div> </div> <div class="btn-group"> <el-button type="danger" v-if="!isFlipped" @click="flipCard">忘记</el-button> <el-button type="success" v-if="!isFlipped" @click="flipCard">认识</el-button> <el-button type="danger" v-if="isFlipped" @click="submitReviewResult(false)">忘记</el-button> <el-button type="success" v-if="isFlipped" @click="submitReviewResult(true)">认识</el-button> </div> </div> </div> <!-- 无可复习单词提示 --> <div v-else style="text-align:center; margin-top: 50px; font-size: 20px; color: #999;"> 无可复习单词,复习完成! </div> <!-- 已选单词弹窗 --> <el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px"> <el-table :data="selectedWords" style="width: 100%;" border @selection-change="handleSelectedChange" > <el-table-column type="selection" width="55" /> <el-table-column prop="id" label="ID" width="80" /> <el-table-column prop="word" label="单词" /> <el-table-column prop="definition" label="释义" /> <el-table-column label="操作" width="100"> <template #default="scope"> <el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button> </template> </el-table-column> </el-table> <template #footer> <span class="dialog-footer"> <el-button @click="selectedDialogVisible = false">关闭</el-button> <el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords"> 批量删除({{ selectedToDelete.length }}) </el-button> </span> </template> </el-dialog> </el-col> <!-- 右侧区域 --> <el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;"> <h2>暂未开发</h2> <p>暂未开发</p> </el-col> <!-- 选择待学习单词弹窗 --> <el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px"> <el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange"> <el-table-column type="selection" width="55" /> <el-table-column prop="word" label="单词" /> <el-table-column prop="definition" label="释义" /> </el-table> <template #footer> <span class="dialog-footer"> <el-button @click="dialogVisible = false">取消</el-button> <el-button type="primary" @click="submitSelectedWords">确认选择({{ selectedToAdd.length }})</el-button> </span> </template> </el-dialog>为什么我批量删除后removeWord,还显示单词卡片
- Assistant
你说“批量删除后调用
removeWord,但页面依然显示单词卡片”,原因很可能是:
核心原因
- 删除操作后数据状态未同步刷新(未及时更新
reviewList)
当前你的删除操作里:
- 删除的是“已选单词”,通过
/study/remove-word或/study/remove-words接口 - 但“单词卡片”展示的是来自
reviewList,是fetchReviewList获取的待复习单词
两者是不同概念的数据:
- 删除“已选单词”不会自动刷新待复习单词列表
- 因此
reviewList依然有数据,页面保持有单词卡片显示
修复办法
批量删除或者单个删除后,应该重新同步刷新待复习单词列表(
reviewList)以及待复习数量(pendingCount)等相关状态具体改法:
在
removeWord和batchRemoveWords的成功回调中,同时调用fetchReviewList()和fetchPendingCount(),刷新待复习卡片数据。
你当前代码变更示例
async function removeWord(row) { const userId = localStorage.getItem('userId') try { await axios.post('/study/remove-word', { userId: Number(userId), wordId: row.wordId || row.id }) await fetchSelectedWords() await fetchPendingCount() // 新增:刷新待复习列表,保证卡片同步刷新 await fetchReviewList() ElMessage.success('删除成功') } catch { ElMessage.error('删除失败') } } async function batchRemoveWords() { const userId = localStorage.getItem('userId') const wordIds = selectedToDelete.value.map(item => item.wordId || item.id) if (!wordIds.length) { ElMessage.warning('请选择要删除的单词') return } try { await axios.post('/study/remove-words', { userId: Number(userId), wordIds }) await fetchSelectedWords() selectedToDelete.value = [] await fetchPendingCount() // 新增:刷新复习列表,保证卡片同步刷新 await fetchReviewList() ElMessage.success('批量删除成功') } catch { ElMessage.error('批量删除失败') } }
另外要确认:
fetchReviewList的接口返回的单词列表是“当前待复习单词”,确认后端删除已选单词数据后,接口数据也会相应变更。- 如果后端接口
/study/review-list没变,前端调用了刷新仍看见旧数据,有缓存或后端未同步删除数据,可能需要后端确认数据删除逻辑正确。
总结
删除“已选单词”后,需要调用刷新待复习列表的接口,更新
reviewList,才能让页面正确反映最新状态,避免旧单词依然显示在卡片上。
如果需要,也可以帮你写更完整的删除+刷新逻辑示例。
- 删除操作后数据状态未同步刷新(未及时更新