NutzCN Logo
问答 [issue 960]org.nutz.dao.Dao.delete这个api实际用起来有些麻烦
发布于 3097天前 作者 wendal 2024 次浏览 复制 上一个帖子 下一个帖子
标签: dao

系统里面想加个通用的删除的方法.最后我得写这么多代码.

    public boolean remove(String apiIocName, Object[] ids) {
        // 不考虑没有主键的情况
                BaseRestFulApi api = getApi(apiIocName);
                Mirror<M> me = Mirror.me(getCurrentCls());
                MappingField mf = this.getEntity(apiIocName).getIdField() != null ? this.entity
                        .getIdField() : this.getEntity(apiIocName).getNameField();
                int i = 0;
                for (Object id : ids) {
                    M born = me.born();
                    mf.setValue(born, id);
                    i += api.getDao().delete(born);
                }
                return i > 0;
            }

原因是通用的api 删除的时候我并不知道对应的class中主键字段 是number (@Id) 还是String (@Name)
所以要写这么多代码判断一下. 感觉有些麻烦 nutzdao 能不能加个方法处理下这种需求?

PS: 关联github issue

4 回复

不知道有没有get到要点, 改造一下(没理解为啥传个apiIocName和每次born一下对象)

    public int delete(String iocName, Object ... keys) {
        int count = 0;
        Object iocobj = null; // 这个iocName就是为了拿dao实例??有多个不同数据源???
        for (Object key : keys) {
            if (key == null)
                continue;
            if (key instanceof Number)
                count += dao().delete(getClass(), ((Number)key).longValue());
            else
                count += dao().delete(getClass(), String.valueOf(key));
        }
        return count;
    }

iocName 确实是为了得到多个数据源用的.确实应该不用每次都born的.我感觉我搞复杂了,你这种实现简单多了,谢谢了

@bugss 那dao()得改回iocobj.getDao()

来自炫酷的 NutzCN

我觉得可以先 where("id = ?") 传入 id 进去然后对结果进行 delete 操作,这样不需要判断是@Id 还是 @Name

添加回复
请先登陆
回到顶部