用ROW_NUMBER() 实现分页功能

本文深入探讨了SQL Server中三种常见的分页技术实现方式,并对其性能进行了详细对比分析,旨在帮助开发者选择最适合其需求的分页策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ECLARE @pagenum AS INT, @pagesize AS INT
SET @pagenum = 2
SET @pagesize = 3
SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY newsid DESC) AS rownum, 
        newsid, topic, ntime, hits
      FROM news) AS D
WHERE rownum BETWEEN (@pagenum-1)*@pagesize+1 AND @pagenum*@pagesize
ORDER BY newsid DESC

aspx里面只需给sql传入pageid和条数即可。

其余分页:

方法1:
适用于 SQL Server 2000/2005

SELECT   TOP  页大小  *
FROM  table1
WHERE  id  NOT   IN
          (
          
SELECT   TOP  页大小 * ( - 1 ) id  FROM  table1  ORDER   BY  id
          )
ORDER   BY  id

方法2:
适用于 SQL Server 2000/2005
SELECT   TOP  页大小  *
FROM  table1
WHERE  id  >
          (
          
SELECT   ISNULL ( MAX (id), 0
          FROM  
                (
                
SELECT   TOP  页大小 * ( - 1 ) id  FROM  table1  ORDER   BY  id
               
A
          )
ORDER   BY  id

方法3:
适用于 SQL Server 2005

SELECT   TOP  页大小  *  
FROM  
        (
        
SELECT  ROW_NUMBER()  OVER  ( ORDER   BY  id)  AS  RowNumber, *   FROM  table1
        A
WHERE  RowNumber  >  页大小 * (页数 - 1 )


说明,页大小:每页的行数;页数:第几页。使用时,请把“页大小”和“页大小*(页数-1)”替换成数字。

 

其它的方案:如果没有主键,可以用临时表,也可以用方案三做,但是效率会低。
建议优化的时候,加上主键和索引,查询效率会提高。

通过SQL 查询分析器,显示比较:我的结论是:
分页方案二:(利用ID大于多少和SELECT TOP分页)效率最高,需要拼接SQL语句
分页方案一:(利用Not In和SELECT TOP分页)   效率次之,需要拼接SQL语句
分页方案三:(利用SQL的游标存储过程分页)    效率最差,但是最为通用

<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>生产计划排程表</title> <style> /* ======= 天空浅蓝主题 ======= */ :root{ --bg:#f5faff; --panel:#fff; --border:#cce7ff; --primary:#3ca9ff; --primary-dark:#0077e6; --primary-light:#e6f4ff; --text:#003366; --text-light:#0077e6; --shadow:rgba(60,169,255,.12); } body{margin:0;background:var(--bg);font-family:"Segoe UI",Arial,"PingFang SC","Microsoft YaHei",sans-serif} .status-container{max-width:98%;margin:22px auto;background:var(--panel);border:1px solid var(--border);padding:22px 18px 30px 18px;border-radius:12px;box-shadow:0 6px 30px var(--shadow);position:relative} .status-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:18px;background:var(--bg)} .status-header h3{color:var(--text-light);letter-spacing:2px} .status-header .btns{display:flex;gap:12px} .btn{padding:7px 18px;border:none;border-radius:4px;font-size:15px;cursor:pointer;background:var(--primary);color:#fff;transition:background .2s} .btn:hover{background:var(--primary-dark)} .btn.modify{background:var(--primary-light);color:var(--text)} .btn.modify:hover{background:var(--primary-dark);color:#fff} .search-box{display:flex;align-items:center;gap:8px} .search-box input{height:32px;border:1px solid var(--primary);border-radius:4px;padding:0 10px;font-size:14px;background:#fff;color:var(--text)} table{width:100%;border-collapse:collapse;font-size:14px;color:var(--text)} thead{background-color:var(--primary-light);color:var(--text)} th,td{border:1px solid var(--border);padding:9px 7px;text-align:center} th{background:var(--primary-light);color:var(--text)} .tag{border-radius:10px;padding:2px 10px;font-size:13px;display:inline-block} .tag-success{color:#21b97a}.tag-danger{color:#f56c6c} /* 弹窗共用 */ .modal-mask{position:fixed;inset:0;background:rgba(0,119,230,.2);z-index:999;display:none} .modal{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);background:#fff;color:var(--text);border-radius:8px;padding:22px;min-width:360px;z-index:1000;display:none} .modal-title{font-weight:bold;font-size:1.18rem;color:var(--primary-dark);margin-bottom:19px} .modal-form-row{display:flex;align-items:center;margin-bottom:13px} .modal-form-row label{width:86px;color:var(--text-light);font-size:14px} .modal-form-row input,.modal-form-row select{flex:1;height:28px;padding:0 7px;border:1px solid var(--primary);border-radius:4px;background:var(--bg);color:var(--text)} .modal-btns{text-align:right;margin-top:18px} .modal-btns .btn{margin-left:12px;background:var(--primary);color:#fff} /* 详情弹窗专属 */ .detail-modal{min-width:800px;max-width:95vw;max-height:90vh;overflow:auto} .detail-modal table th,.detail-modal table td{color:var(--text);border:1px solid var(--border);padding:6px 4px;min-width:90px;background:#fff} .detail-modal input[type=number]{width:100%;border:1px solid var(--border);border-radius:3px;padding:4px;background:#fff;color:var(--text)} .detail-btns{margin-top:15px;text-align:right} /* 分页 */ .pager-box{display:flex;align-items:center;gap:8px;position:absolute;right:22px;bottom:-80px;background:var(--primary-light);padding:6px 10px;border-radius:6px;box-shadow:0 2px 8px var(--shadow);font-size:14px;color:var(--text-light)} .pager-label input{width:46px;height:24px;text-align:center;border:1px solid var(--primary);border-radius:4px;margin:0 4px;background:#fff;color:var(--text-light)} </style> </head> <body> <div class="status-container"> <div class="status-header"> <h3>生产计划排程表</h3> <div class="btns"> <div class="search-box"> <input type="text" id="searchInput" placeholder="工序、负责人、产品名称...关键词查询"> <button class="btn" onclick="searchPlans()">查询</button> </div> <button class="btn" onclick="openAddModal()">增加</button> </div> </div> <table> <thead> <tr> <th>序号</th><th>工序</th><th>接单日期</th><th>负责人</th><th>订单跟踪号</th><th>产品代码</th> <th>产品名称</th><th>订单量</th><th>GTM出货日期</th><th>工厂入库日期</th><th>是否延误</th> <th>累计交付</th><th>待交付</th><th>结单情况</th><th>排程日期</th><th>备注</th><th>操作</th> </tr> </thead> <tbody id="planTableBody"><tr><td colspan="17">加载中...</td></tbody> </table> <div id="pagerBox" class="pager-box"> <button class="btn" id="btnPrev" onclick="prevPage()">上一页</button> <label class="pager-label"> 第<input type="number" id="pageInput" min="1" max="1" value="1" onkeydown="if(event.key==='Enter') jumpToPage()">页 / 共<span id="totalPages">1</span>页 </label> <button class="btn" id="btnNext" onclick="nextPage()">下一页</button> <button class="btn modify" onclick="jumpToPage()">跳转</button> </div> </div> <!-- 原有增删改弹窗 --> <div class="modal-mask" id="modalMask"></div> <div class="modal" id="modalBox"> <div class="modal-title" id="modalTitle">新增排程</div> <form id="modalForm"> <div class="modal-form-row"><label>工序</label><input type="text" name="processName" required></div> <div class="modal-form-row"><label>接单日期</label><input type="date" name="startDate"></div> <div class="modal-form-row"><label>负责人</label><input type="text" name="leader" required></div> <div class="modal-form-row"><label>订单跟踪号</label><input type="text" name="orderTrackingNo" required></div> <div class="modal-form-row"><label>产品代码</label><input type="text" name="productCode" required></div> <div class="modal-form-row"><label>产品名称</label><input type="text" name="productName" required></div> <div class="modal-form-row"><label>订单量</label><input type="number" name="orderQuantity" required></div> <div class="modal-form-row"><label>GTM出货日期</label><input type="date" name="shipmentDate"></div> <div class="modal-form-row"><label>工厂入库日期</label><input type="date" name="finishDate"></div> <div class="modal-form-row"><label>是否延误</label> <select name="isDelayed"><option value="1">是</option><option value="0">否</option></select></div> <div class="modal-form-row"><label>累计交付</label><input type="number" name="deliveredQty"></div> <div class="modal-form-row"><label>待交付</label><input type="number" name="pendingQty"></div> <div class="modal-form-row"><label>结单情况</label><input type="text" name="receiveStatus"></div> <div class="modal-form-row"><label>排程日期</label><input type="date" name="scheduleDate"></div> <div class="modal-form-row"><label>备注</label><input type="text" name="remark"></div> <div class="modal-btns"> <button type="button" class="btn" onclick="closeModal()">取消</button> <button type="submit" class="btn modify" id="modalSubmitBtn">保存</button> </div> </form> </div> <!-- ===== 新增:详情弹窗 ===== --> <div class="modal-mask" id="detailMask" style="display:none"></div> <div class="modal detail-modal" id="detailWrap" style="display:none"> <div class="modal-title">排程详情</div> <p>订单跟踪号:<span id="detailOrderNo"></span> &nbsp;&nbsp; 产品名称:<span id="detailProductName"></span></p> <div style="overflow-x:auto"> <table id="detailTable"> <thead><tr id="detailHeadRow"></tr></thead> <tbody> <tr id="plannedRow"><td><b>计划交付</b></td></tr> <tr id="actualRow"><td><b>实际交付</b></td></tr> </tbody> </table> </div> <div class="modal-btns"> <button class="btn modify" onclick="saveDetail()">保存</button> <button class="btn" onclick="closeDetail()">关闭</button> </div> </div> <script> let editingId=null,allPlans=[],currentPage=1,totalPages=1; async function loadPlans(k,p){const t=document.getElementById('planTableBody');t.innerHTML='<tr><td colspan="17">加载中...</td></tr>';try{let u=`http://localhost:8080/api/production_plans?page=${p}&size=10`;if(k)u+=`&keyword=${encodeURIComponent(k)}`;const r=await fetch(u),d=await r.json();allPlans=d.records;renderPlans(d.records);toggleOperationColumn();currentPage=d.current;totalPages=d.pages;updatePager();}catch{t.innerHTML='<tr><td colspan="17">加载失败</td></tr>'}} function renderPlans(d){const t=document.getElementById('planTableBody');if(!Array.isArray(d)||d.length===0){t.innerHTML='<tr><td colspan="17">暂无数据</td></tr>';return;}t.innerHTML=d.map(r=>`<tr> <td>${r.id}</td><td>${r.processName||'-'}</td><td>${r.startDate||'-'}</td><td>${r.leader||'-'}</td><td>${r.orderTrackingNo||'-'}</td> <td>${r.productCode||'-'}</td><td>${r.productName||'-'}</td><td>${r.orderQuantity??'-'}</td><td>${r.shipmentDate||'-'}</td> <td>${r.finishDate||'-'}</td><td><span class="tag ${r.isDelayed>0?'tag-danger':'tag-success'}">${r.isDelayed>0?'是':'否'}</span></td> <td>${r.deliveredQty??'-'}</td><td>${r.pendingQty??'-'}</td><td>${r.receiveStatus||'-'}</td> <td><button class="btn modify" onclick="openDetail(${r.id})">查看详情</button></td> <td>${r.remark||'-'}</td> <td><button class="btn modify" onclick="openEditModal(${r.id})">修改</button><button class="btn" style="margin-left:6px;background:#f56c6c" onclick="deletePlan(${r.id})">删除</button></td> </tr>`).join('')} function toggleOperationColumn(){const role=localStorage.getItem('role');const head=document.querySelector('th:last-child'),cells=document.querySelectorAll('td:last-child');if(role==='ADMIN'){head.style.display='';cells.forEach(c=>c.style.display='')}else{head.style.display='none';cells.forEach(c=>c.style.display='none')}} function searchPlans(){loadPlans(document.getElementById('searchInput').value.trim(),1)} function updatePager(){const i=document.getElementById('pageInput');i.max=totalPages;i.value=currentPage;document.getElementById('totalPages').textContent=totalPages;document.getElementById('btnPrev').disabled=currentPage<=1;document.getElementById('btnNext').disabled=currentPage>=totalPages} function prevPage(){if(currentPage>1)loadPlans(document.getElementById('searchInput').value.trim(),currentPage-1)} function nextPage(){if(currentPage<totalPages)loadPlans(document.getElementById('searchInput').value.trim(),currentPage+1)} function jumpToPage(){const v=parseInt(document.getElementById('pageInput').value,10);if(isNaN(v)||v<1||v>totalPages)return;loadPlans(document.getElementById('searchInput').value.trim(),v)} function openAddModal(){editingId=null;resetModal('新增排程')} function openEditModal(id){editingId=id;const r=allPlans.find(p=>p.id===id);if(!r)return;resetModal('修改排程',r)} function resetModal(title,data={}){document.getElementById('modalTitle').textContent=title;const f=document.getElementById('modalForm');f.reset();for(const k in data)if(f[k])f[k].value=data[k];document.getElementById('modalMask').style.display='block';document.getElementById('modalBox').style.display='block'} function closeModal(){document.getElementById('modalMask').style.display='none';document.getElementById('modalBox').style.display='none'} document.getElementById('modalMask').onclick=closeModal; document.getElementById('modalForm').onsubmit=async e=>{e.preventDefault();const fd=new FormData(e.target),data=Object.fromEntries(fd);data.isDelayed=data.isDelayed==='1';['orderQuantity','deliveredQty','pendingQty'].forEach(k=>{if(data[k])data[k]=Number(data[k])});try{const url=editingId?`/api/production_plans/${editingId}`:'/api/production_plans',meth=editingId?'PUT':'POST';const res=await fetch(url,{method:meth,headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});if(res.ok){closeModal();loadPlans('',currentPage)}else alert('保存失败')}catch{alert('网络异常')}} async function deletePlan(id){if(!confirm(`确定删除排程 ${id} 吗?`))return;try{const res=await fetch(`/api/production_plans/${id}`,{method:'DELETE'});if(res.ok){loadPlans(document.getElementById('searchInput').value.trim(),currentPage)}else alert('删除失败')}catch{alert('网络异常')}} /* ================= 新增详情弹窗逻辑 ================= */ let curDetailPlanId = null; /* ================= 新增详情弹窗逻辑(含星期几行) ================= */ async function openDetail(planId) { curDetailPlanId = planId; const plan = allPlans.find(p => p.id === planId); if (!plan) return; document.getElementById('detailOrderNo').textContent = plan.orderTrackingNo; document.getElementById('detailProductName').textContent = plan.productName; /* 1. 生成最近 30 天日期 */ const dates = []; const today = new Date(); for (let i = 0; i < 30; i++) { const d = new Date(today); d.setDate(today.getDate() + i); dates.push(d.toISOString().slice(0, 10)); } /* 2. 读取已保存数据 */ let saved = {}; try { const res = await fetch(`/api/production_plans/${planId}/details`); if (res.ok) (await res.json()).forEach(it => (saved[it.date] = it)); } catch (e) { /* ignore */ } /* 3. 计算星期几(0=周日 … 6=周六) */ const weekMap = ['日', '一', '二', '三', '四', '五', '六']; const weekRowHTML = dates .map(d => `<td>周${weekMap[new Date(d + 'T00:00:00').getDay()]}</td>`) .join(''); /* 4. 渲染表头 */ const headRow = document.getElementById('detailHeadRow'); headRow.innerHTML = '<th></th>' + dates.map(d => `<th>${d}</th>`).join(''); /* 5. 渲染星期、计划、实际三行 */ const tbody = document.querySelector('#detailTable tbody'); tbody.innerHTML = `<tr id="weekRow"><td><b>星期</b></td>${weekRowHTML}</tr>` + `<tr id="plannedRow"><td><b>计划交付</b></td>${dates .map( d => `<td><input type="number" min="0" value="${saved[d]?.plannedQty || 0}" data-date="${d}" data-type="planned"></td>` ) .join('')}</tr>` + `<tr id="actualRow"><td><b>实际交付</b></td>${dates .map( d => `<td><input type="number" min="0" value="${saved[d]?.actualQty || 0}" data-date="${d}" data-type="actual"></td>` ) .join('')}</tr>`; /* 6. 显示弹窗 */ document.getElementById('detailMask').style.display = 'block'; document.getElementById('detailWrap').style.display = 'block'; } function closeDetail(){ document.getElementById('detailMask').style.display='none'; document.getElementById('detailWrap').style.display='none'; } async function saveDetail(){ const inputs = document.querySelectorAll('#detailTable input'); const payload = {}; inputs.forEach(inp=>{ const date = inp.dataset.date; const type = inp.dataset.type; if(!payload[date]) payload[date] = {date, plannedQty:0, actualQty:0}; payload[date][type] = parseInt(inp.value) || 0; }); await fetch(`/api/production_plans/${curDetailPlanId}/details`,{ method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(Object.values(payload)) }); alert('已保存'); closeDetail(); } /* ================= 初始化 ================= */ loadPlans('',1); </script> </body> </html>这是我的前端界面,请帮我实现点击查看详情按钮后的后端接口,要求当录入数据并保存后上面的日期就不会随着时间变更
最新发布
07-20
<think>根据用户需求,需要设计一个后端接口用于保存生产计划详情,并且要求保存的日期数据不会随时间变动。这意味着我们需要在保存时记录当时的日期,并且后续读取时始终返回该固定日期,而不是动态变化的日期。 设计思路: 1. 在数据库表中,除了存储用户输入的日期字段外,还需要一个字段来记录实际的保存日期(例如saved_date),这个字段在数据创建时由后端自动设置为当前日期,并且之后不再更新。 2. 用户在前端看到的日期应该是他们当时录入的日期,而不是当前日期。因此,我们需要保存两个日期: - 用户录入的日期(例如plan_date) - 数据保存的日期(saved_date,用于记录操作时间,但不需要展示给用户) 但是,用户要求“保存的日期数据不会随时间变更”指的是用户录入的日期在保存后就不应该再改变。因此,我们只需要在保存时记录用户录入的日期,并且后续读取时返回该日期即可。 然而,用户可能担心的是:如果录入的日期是未来日期,那么当时间过了那一天,再查看时日期会不会变成过去日期?实际上,我们保存的是用户录入的那个日期值,不管时间如何流逝,该值都是固定的。 所以,我们不需要额外存储一个固定日期的字段,只需要将用户录入的日期原样保存,并且在后续查询中返回该日期即可。 但是,如果用户要求的是在保存时记录当时的实际日期(比如操作日期),并且这个日期以后不再变化,那么我们就需要额外存储一个操作日期字段(例如operation_date),该字段在创建记录时由后端自动设置为当前日期,并且不允许修改。 根据问题描述,用户要求的是“录入数据保存后日期不会随着时间变更”,这里应该是指用户录入的日期(比如计划日期)在保存后就不再变化,而不是指操作日期。因此,我们只需要确保用户录入的日期被正确保存,并且在后续读取时返回该值即可。 然而,问题中还有一句:“保证保存的日期数据不会随时间变动”。这里可能有两种理解: 1. 用户录入的日期在保存后不会再被修改(即数据不变)。 2. 用户希望保存的日期值不会因为时间的流逝而自动变化(例如,今天保存的日期是2023-10-10,过了几天查看还是2023-10-10,而不是变成当前日期)。 我们按照第二种理解,即保存的日期值就是用户录入的值,不会因为时间变化而改变。所以,我们只需要保存用户录入的日期,并且在返回时原样返回。 因此,后端接口设计如下: 1. 创建生产计划详情接口(POST /api/production-plans) 2. 更新生产计划详情接口(PUT /api/production-plans/{id}) 在创建和更新时,接收用户提交的日期字段(例如planDate),并保存到数据库。在查询时,返回该字段。 但是,如果用户没有录入日期,我们可能需要根据业务需求设置默认值(比如当前日期)?但根据要求,用户录入的日期在保存后不会变化,所以如果用户录入了,就存用户录入的;如果没录入,那么保存操作日期(作为默认值)也是固定的。 根据问题,我们假设用户会录入日期。 数据库表设计(以MySQL为例): ```sql CREATE TABLE production_plan_detail ( id INT PRIMARY KEY AUTO_INCREMENT, plan_date DATE NOT NULL, -- 用户录入的计划日期,保存后不变 ... 其他字段, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- 创建时间(记录操作时间,可用于追踪) updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP -- 更新时间 ); ``` 在创建记录时,将用户提交的plan_date存入数据库。后续更新时,如果用户修改了plan_date,则更新为新的值(如果业务允许修改)。如果业务不允许修改,则更新接口中忽略该字段。 接口设计(以Spring Boot为例): 1. 创建接口: ```java @PostMapping("/api/production-plans") public ResponseEntity<?> createProductionPlan(@RequestBody ProductionPlanDetailRequest request) { // 将request中的planDate等字段保存到数据库 ProductionPlanDetail detail = new ProductionPlanDetail(); detail.setPlanDate(request.getPlanDate()); // 用户传入的日期 // ... 设置其他字段 productionPlanService.save(detail); return ResponseEntity.ok().build(); } ``` 2. 更新接口: ```java @PutMapping("/api/production-plans/{id}") public ResponseEntity<?> updateProductionPlan(@PathVariable Long id, @RequestBody ProductionPlanDetailRequest request) { ProductionPlanDetail detail = productionPlanService.findById(id); // 更新用户传入的日期(如果业务允许修改) detail.setPlanDate(request.getPlanDate()); // ... 更新其他字段 productionPlanService.save(detail); return ResponseEntity.ok().build(); } ``` 3. 返回的数据模型: ```java public class ProductionPlanDetailResponse { private Long id; private Date planDate; // 用户录入的日期,不会随时间变化,返回的就是当时保存的值 // ... 其他字段 } ``` 注意:这里使用Date类型,实际开发中建议使用LocalDate(Java8以上)。 这样,无论时间如何流逝,返回给前端的planDate都是当初保存的值。 但是,如果用户希望保存的是操作当天的日期,并且以后不再变化(即使过了很多天,看到的还是操作当天的日期),那么我们就需要在创建记录时,将当前日期作为planDate保存(如果用户没有输入的话),或者单独用一个字段(如operationDate)来保存操作日期,并且这个字段由后端自动生成,不允许用户传入。 根据问题描述,用户要求的是“录入数据保存后日期不会随着时间变更”,所以应该是用户自己录入的日期,我们原样保存即可。 因此,按照上述设计即可满足需求。 另外,如果用户要求的是在保存时记录当时的日期(作为计划日期),并且以后不再变化,那么我们可以这样做: - 在创建接口中,忽略用户传入的planDate(如果有的话),而由后端自动设置为当前日期。 - 这样,无论用户传入什么日期,我们都将计划日期设置为创建记录的当天。 但是,这样就不能让用户自己指定计划日期了。所以,我们需要明确需求。 根据问题,用户要求的是“录入数据”,所以应该是允许用户自己输入日期的。因此,我们采用第一种方式:保存用户输入的日期,并且该日期在保存后不会自动变化。 综上所述,后端接口设计要点: 1. 接收用户传入的日期字段(如planDate) 2. 将该字段原样保存到数据库 3. 在查询时,返回该字段的值(即用户当时录入的值) 这样,无论时间如何流逝,该日期都不会变化。 最后,关于数据校验:我们可以对传入的日期进行合法性校验(比如不能是过去日期,或者格式校验等),但这属于业务逻辑,根据实际需求而定。 示例请求体(JSON): ```json { "planDate": "2024-12-31", // 用户录入的日期 // ... 其他字段 } ``` 示例响应体(查询时): ```json { "id": 1, "planDate": "2024-12-31", // ... 其他字段 } ``` 这样设计即可满足需求。</think>### 后端接口设计:生产计划详情保存功能(固定日期不变) #### 核心设计思路 1. **日期固化原则**:在数据保存时立即将日期值转换为不可变的字符串格式 2. **双重存储机制**: - 原始日期字段:存储用户录入的原始日期值 - 固化日期字段:存储格式化的固定日期字符串 3. **数据校验**:确保日期格式合法且符合业务逻辑 #### 数据库表设计 ```sql CREATE TABLE production_plan_details ( id BIGINT AUTO_INCREMENT PRIMARY KEY, plan_id VARCHAR(36) NOT NULL COMMENT '关联的生产计划ID', -- 原始日期字段 original_due_date DATE NOT NULL COMMENT '用户录入的原始交期', -- 固化日期字段 fixed_due_date VARCHAR(10) NOT NULL COMMENT '固化后的日期(YYYY-MM-DD)', material_code VARCHAR(50) NOT NULL COMMENT '物料编码', required_quantity INT NOT NULL COMMENT '需求数量', process_stage ENUM('cutting', 'welding', 'assembly') NOT NULL COMMENT '生产阶段', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, INDEX idx_plan_id (plan_id) ) COMMENT '生产计划详情表'; ``` #### 后端接口实现(Spring Boot示例) ##### 1. DTO设计(请求参数封装) ```java @Data @Builder public class ProductionDetailRequest { @NotNull(message = "计划ID不能为空") private String planId; @FutureOrPresent(message = "交期不能是过去日期") @JsonFormat(pattern = "yyyy-MM-dd") private Date dueDate; @NotBlank(message = "物料编码不能为空") private String materialCode; @Min(value = 1, message = "数量必须大于0") private Integer requiredQuantity; @NotBlank(message = "生产阶段不能为空") private String processStage; } ``` ##### 2. 服务层实现(日期固化逻辑) ```java @Service @RequiredArgsConstructor public class ProductionDetailService { private final ProductionDetailRepository repository; @Transactional public ProductionDetail saveDetail(ProductionDetailRequest request) { // 日期固化处理 String fixedDate = formatAndFixDate(request.getDueDate()); ProductionDetail detail = ProductionDetail.builder() .planId(request.getPlanId()) .originalDueDate(request.getDueDate()) .fixedDueDate(fixedDate) // 存储固化日期 .materialCode(request.getMaterialCode()) .requiredQuantity(request.getRequiredQuantity()) .processStage(request.getProcessStage()) .build(); return repository.save(detail); } // 日期固化方法 private String formatAndFixDate(Date date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(date); // 转换为固定字符串格式 } } ``` ##### 3. 控制器层 ```java @RestController @RequestMapping("/api/production-details") @RequiredArgsConstructor public class ProductionDetailController { private final ProductionDetailService detailService; @PostMapping public ResponseEntity<ApiResponse> saveDetail( @Valid @RequestBody ProductionDetailRequest request ) { ProductionDetail savedDetail = detailService.saveDetail(request); return ResponseEntity.ok(ApiResponse.success("保存成功", savedDetail)); } @GetMapping("/{planId}") public ResponseEntity<ApiResponse> getDetailsByPlan( @PathVariable String planId ) { List<ProductionDetail> details = detailService.getByPlanId(planId); return ResponseEntity.ok(ApiResponse.success(details)); } } ``` #### 关键特性说明 1. **日期固化机制**: - 在`formatAndFixDate()`方法中将`Date`对象转为`yyyy-MM-dd`字符串 - 存储后不再随系统时间变化 - 查询时直接返回字符串值 2. **数据一致性保证**: ```java // 更新时禁止修改固化日期 @Transactional public void updateDetail(Long id, ProductionDetailRequest request) { ProductionDetail detail = repository.findById(id).orElseThrow(); // 禁止修改固化日期字段 detail.setRequiredQuantity(request.getRequiredQuantity()); // ...其他可更新字段 } ``` 3. **响应数据结构: ```json { "code": 200, "message": "保存成功", "data": { "id": 123, "planId": "PLAN-2023-001", "originalDueDate": "2023-12-31", "fixedDueDate": "2023-12-31", "materialCode": "MAT-001", "requiredQuantity": 1000, "processStage": "assembly" } } ``` #### 前端调用示例 ```javascript // 保存生产计划详情 async function saveProductionDetail() { const detailData = { planId: "PLAN-2023-001", dueDate: "2023-12-31", // 用户选择的日期 materialCode: "MAT-001", requiredQuantity: 1000, processStage: "assembly" }; try { const response = await fetch('/api/production-details', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(detailData) }); const result = await response.json(); console.log('保存结果:', result); } catch (error) { console.error('保存失败:', error); } } ``` #### 数据流示意图 ```mermaid sequenceDiagram participant Frontend as 前端 participant Controller as 后端控制器 participant Service as 服务层 participant Repository as 数据库 Frontend->>Controller: POST /details (含日期数据) Controller->>Service: 传递DTO对象 Service->>Service: 执行日期固化(formatAndFixDate) Service->>Repository: 保存实体(含固化日期) Repository-->>Service: 返回保存结果 Service-->>Controller: 返回响应DTO Controller-->>Frontend: 返回成功响应 ``` ### 设计优势 1. **日期不变性**:通过字符串存储确保日期值永不变化 2. **数据追溯**:同时保存原始日期和固化日期 3. **兼容性**: - 前端仍使用标准日期选择器 - 后端自动处理转换逻辑 4. **审计能力**:通过`created_at`/`updated_at`跟踪操作时间 5. **校验保障**:确保业务规则合规性[^3] ### 注意事项 1. **时区处理**:在应用层统一使用UTC时间避免时区问题 ```java @Bean public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() { return builder -> builder.timeZone(TimeZone.getTimeZone("UTC")); } ``` 2. **历史数据迁移**:已有数据需执行固化处理脚本 ```sql UPDATE production_plan_details SET fixed_due_date = DATE_FORMAT(original_due_date, '%Y-%m-%d'); ``` 3. **查询优化**:固化日期字段可建立索引提高查询效率
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值