难怪程序员越老越值钱了,想来我已经在开发这个行业做了有三四年了,现在写起代码来,真的是越来越精湛了,我也不想这样赤裸裸的自夸,但是真的是发自肺腑的感叹,因为的确写的比以前好了。
最近写了一个批量操作的功能,以前都是页面上传需要处理的对象id集合,后台获取对象list,然后遍历集合一个一个的操作对象。以前也没有想过为什么要这么做,这样做有什么优点或者缺点,除了这么做还有没有别的做法,反正大家都是这么做的,而且能实现功能,不加思考复制粘贴修改,快速的完成手上的工作。这次我写代码的时候,突然意识到,为什么要这么写,明明有update语句,执行一句sql就能完成的事,为什么要费那么大功夫拿到一个一个的对象,然后一个一个的去处理,这样效率也太低了。于是这一次,我决定不再复制粘贴,而是要自己用另一套方案去完成这个批量操作的功能。写完后发现新的思路让代码更加简洁,而且还提高了代码的执行效率,简直堪称。。。算了,自夸的话也不想多说了,看代码吧(DeviceRegisterAction.java):
<s:span id="deviceBatch" style="float: right; margin-top: 20px;"><h:outputLink style="margin-left:5px;" value="javascript:;" rendered="#{deviceRegisterAction.state eq 'out'}" > <i class="icon-plus" /> <h:outputText value="批量添加" /> <a:param name="page" value="#{param.page}" /> <a:param name="orgzid" value="#{param.orgzid}" /> <a:param name="ecardstatusid" value="#{param.ecardstatusid}" /> <a:param name="cardnumber" value="#{param.cardnumber}" /> <a:ajax event="click" execute="@form" render="deviceTable,devicePagingId" listener="#{deviceRegisterAction.addToMonitorGroupBatch()}" /> </h:outputLink> <h:outputLink style="margin-left:5px;" value="javascript:;" rendered="#{deviceRegisterAction.state eq 'in'}" > <i class="icon-remove" /> <h:outputText value="批量删除" /> <a:param name="page" value="#{param.page}" /> <a:ajax event="click" execute="@form" render="deviceTable,devicePagingId" listener="#{deviceRegisterAction.deleteFromMonitorGroupBatch()}" /> </h:outputLink></s:span> <h:outputLink value="javascript:;" style="margin-left: 5px; float: right; margin-top: 20px;" onclick="invert_in();"> <i class="icon-minus-sign" /> <h:outputText value="反选" /> </h:outputLink> <h:outputLink value="javascript:;" style="margin-left: 5px; float: right; margin-top: 20px;" onclick="select_in();"> <i class="icon-ok-circle" /> <h:outputText value="全选" /> </h:outputLink>
public void deleteFromMonitorGroupBatch() { batch(null); } public void addToMonitorGroupBatch() { batch(currMonitorGroup.getId()); } private void batch(Long id) { List<Long> idList = map2list(); if (idList.size() == 0) { getStatusMessages().addFromResourceBundle(Severity.INFO, "至少选择一个!"); return; } StringBuffer findSql = new StringBuffer(200); findSql.append(" update DeviceRegister u set u.monitorGroup.id = :groupid where 1=1 "); findSql.append(" and u.id in :idList "); Query findQuery = em.createQuery(findSql.toString()); findQuery.setParameter("idList", idList); findQuery.setParameter("groupid", id); findQuery.executeUpdate(); deviceSelectMap.clear(); initDeviceRegisterList(currMonitorGroup); } private List<Long> map2list() { List<Long> idList = new ArrayList<Long>(); if (deviceSelectMap == null) { return idList; } for (Long key : deviceSelectMap.keySet()) { if (deviceSelectMap.get(key)) { idList.add(key); } } return idList; }