java 19 -2 异常以及tr...catch()的方法处理异常

本文深入解析Java中的异常处理机制,包括Error与Exception的区别,RuntimeException与其他异常的处理方式,以及try...catch...finally语句的使用技巧。通过生动的比喻和实例,帮助读者理解异常处理的重要性和正确实践。

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

  1 /*
  2   异常:程序出现了不正常的情况。
  3   
  4   举例:今天天气很好,班长出去旅游。骑着自行车,去山里面呼吸新鲜空气。
  5 Error:
  6         问题1:山路塌陷了,班长及时停住了,但是过不去了。严重的问题。(Error,编译处理不了的)
  7 Exception:
  8         问题2:班长出门推自行车,发现气没了,把气吹起来。出发前就应该检查的问题。(非RuntimeException的异常,必须处理)
  9           问题3:班长骑着车在山路上惬意的行驶着,山路两边是有小石子的,中间是平坦的水泥路。(RuntimeException 需要修正代码)
 10               一直在平坦的水泥路上行驶是没有任何问题的,但是呢,他偏偏喜欢骑到小石子上,结果爆胎了。旅游的过程中出现的问题。
 11               no zuo no die。
 12   
 13 程序的异常:Throwable
 14     严重问题:Error   是程序本身无法恢复的严重错误,无法处理
 15     问题:Exception 表示可以被程序捕获并处理的异常错误
 16         编译期问题:不是RuntimeException的异常 必须进行处理的,因为你不处理,编译就不能通过。
 17         运行期问题: RuntimeException  这个问题出现肯定是我们的代码不够严谨,需要修正代码的。
 18   
 19   如何程序出现了问题,我们没有做任何处理,最终jvm会做出默认的处理。
 20   把异常的名称,原因及出现的问题等信息输出在控制台。
 21   同时会结束程序。
 22  
 23 我们自己如何处理异常呢?
 24   A:try...catch...finally
 25   B:throws 抛出
 26   
 27   try...catch...finally的处理格式:
 28           try {
 29               可能出现问题的代码;
 30           }catch(异常名 变量) {
 31               针对问题的处理;
 32           }finally {
 33               释放资源;
 34           }
 35   
 36   变形格式:
 37           try {
 38               可能出现问题的代码;
 39           }catch(异常名 变量) {
 40               针对问题的处理;
 41           }
 42   
 43   注意:
 44           A:try里面的代码越少越好(因为jvm会针对try里面的代码开辟另外的空间,所以越少越好,省空间)
 45           B:catch里面必须有内容,哪怕是给出一个简单的提示(不然就不是处理问题,而是隐藏问题了)
 46     
 47     A:一个异常
 48   B:二个异常的处理
 49           a:每一个写一个try...catch
 50     b:写一个try,多个catch
 51               try{
 52                   ...
 53               }catch(异常类名 变量名) {
 54                   ...
 55               }
 56               catch(异常类名 变量名) {
 57                   ...
 58               }
 59               ...
 60   
 61         注意事项:
 62                   1:能明确的尽量明确,不要用大的来处理。
 63                   2:平级关系的异常谁前谁后无所谓,如果出现了子父关系,父必须在后面。
 64   
 65     注意:
 66           一旦try里面出了问题,就会在这里把问题给抛出去,然后和catch里面的问题进行匹配,
 67           一旦有匹配的,就执行catch里面的处理,然后结束了try...catch
 68           继续执行后面的语句。
 69  */
 70 
 71  public class ExceptionDemo2 {
 72     public static void main(String[] args) {
 73         // method1();
 74 
 75         // method2();
 76 
 77         // method3();
 78 
 79         method4();
 80     }
 81 
 82     public static void method4() {
 83         int a = 10;
 84         int b = 0;
 85         int[] arr = { 1, 2, 3 };
 86 
 87         // 爷爷在最后
 88         try {
 89             System.out.println(a / b);
 90             System.out.println(arr[3]);
 91             System.out.println("这里出现了一个异常,你不太清楚是谁,该怎么办呢?");
 92         } catch (ArithmeticException e) {
 93             System.out.println("除数不能为0");
 94         } catch (ArrayIndexOutOfBoundsException e) {
 95             System.out.println("你访问了不该的访问的索引");
 96         } catch (Exception e) {
 97             System.out.println("出问题了");
 98         }
 99 
100         // 爷爷在前面是不可以的
101         // try {
102         // System.out.println(a / b);
103         // System.out.println(arr[3]);
104         // System.out.println("这里出现了一个异常,你不太清楚是谁,该怎么办呢?");
105         // } catch (Exception e) {
106         // System.out.println("出问题了");
107         // } catch (ArithmeticException e) {
108         // System.out.println("除数不能为0");
109         // } catch (ArrayIndexOutOfBoundsException e) {
110         // System.out.println("你访问了不该的访问的索引");
111         // }
112 
113         System.out.println("over");
114     }
115 
116     // 两个异常的处理
117     public static void method3() {
118         int a = 10;
119         int b = 0;
120         int[] arr = { 1, 2, 3 };
121 
122         try {
123             System.out.println(arr[3]);
124             System.out.println(a / b);
125             // System.out.println(arr[3]);
126         } catch (ArithmeticException e) {
127             System.out.println("除数不能为0");
128         } catch (ArrayIndexOutOfBoundsException e) {
129             System.out.println("你访问了不该的访问的索引");
130         }
131 
132         System.out.println("over");
133     }
134 
135     // 两个异常
136     public static void method2() {
137         int a = 10;
138         int b = 0;
139         try {
140             System.out.println(a / b);
141         } catch (ArithmeticException e) {
142             System.out.println("除数不能为0");
143         }
144 
145         int[] arr = { 1, 2, 3 };
146         try {
147             System.out.println(arr[3]);
148         } catch (ArrayIndexOutOfBoundsException e) {
149             System.out.println("你访问了不该的访问的索引");
150         }
151 
152         System.out.println("over");
153     }
154 
155     // 一个异常
156     public static void method1() {
157         // 第一阶段
158         int a = 10;
159         // int b = 2;
160         int b = 0;
161 
162         try {
163             System.out.println(a / b);
164         } catch (ArithmeticException ae) {
165             System.out.println("除数不能为0");
166         }
167 
168         // 第二阶段
169         System.out.println("over");
170     }
171 }

 

转载于:https://www.cnblogs.com/LZL-student/p/5914481.html

<!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>    产品名称:<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、付费专栏及课程。

余额充值