最近有一个需求是实现一个表格中记录的上下移动如下图所示
选择其中一项,点击上下移动则则可以对记录上下移动。
这个项目使用的是jsf+hibernate+spring实现的
liteBean中的内容:
/** * 上移一条记录 */ @Action(id = "up", event = "onclick") public void up() { Object[] objs = grid.getSelectedValues(); if (objs == null || objs.length == 0) { Browser.execClientScript("window.alert('请选择一条记录!');"); return; } selectedRowData = objs[0]; DictionaryItem dicItem = (DictionaryItem) selectedRowData; if (null != dictionaryItemService.upExchange(dicItem)) { Browser.alert("第一条不能再上移"); } reload(); } /** * 下移一条记录 */ @Action(id = "down", event = "onclick") public void down() { Object[] objs = grid.getSelectedValues(); if (objs == null || objs.length == 0) { Browser.execClientScript("window.alert('请选择一条记录!');"); return; } selectedRowData = objs[0]; DictionaryItem dicItem = (DictionaryItem) selectedRowData; if (null != dictionaryItemService.downExchange(dicItem)) { Browser.alert("最后一条不能再下移"); } reload(); }
在service层得代码:
@Override public String upExchange(DictionaryItem dicItem) { long order = dicItem.getOrder(); DictionaryItem nextDicItem = dictionaryItemDao.nextItem(order); if(nextDicItem!=null){ long nextOrder = nextDicItem.getOrder(); long number = order; order = nextOrder; nextOrder = number; dicItem.setOrder(order); nextDicItem.setOrder(nextOrder); modify(dicItem); modify(nextDicItem); return null; } return EXCHANG_ERROR; } @Override public String downExchange(DictionaryItem dicItem) { long order = dicItem.getOrder(); DictionaryItem preDicItem = dictionaryItemDao.preItem(order); if(preDicItem!=null){ long nextOrder = preDicItem.getOrder(); long number = order; order = nextOrder; nextOrder = number; dicItem.setOrder(order); preDicItem.setOrder(nextOrder); modify(dicItem); modify(preDicItem); return null; } return EXCHANG_ERROR; }
dao层得代码
@Override public DictionaryItem nextItem(long order) { final long nextOrder = order; final String sql = "from DictionaryItem dictionaryItem where dictionaryItem.order>? order by dictionaryItem.order asc"; return (DictionaryItem) this.getHibernateTemplate().execute( new HibernateCallback() { @Override public DictionaryItem doInHibernate(Session session) throws HibernateException, SQLException { DictionaryItem obj = (DictionaryItem) session .createQuery(sql).setLong(0, nextOrder) .setMaxResults(1).uniqueResult(); return obj; } }); } @Override public DictionaryItem preItem(long order) { final long preOrder = order; final String sql = "from DictionaryItem dictionaryItem where dictionaryItem.order<? order by dictionaryItem.order desc"; return (DictionaryItem) this.getHibernateTemplate().execute( new HibernateCallback() { @Override public DictionaryItem doInHibernate(Session session) throws HibernateException, SQLException { DictionaryItem obj = (DictionaryItem) session .createQuery(sql).setLong(0, preOrder) .setMaxResults(1).uniqueResult(); return obj; } }); }