Dorado 7 : 14.3.3.2 准备后台服务

步骤1:在com.bstek.dorado.sample.standardlesson.service.DeptService类中增加saveAll方法,最终代码如下:

package com.bstek.dorado.sample.standardlesson.service;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.sample.standardlesson.dao.SlDeptDao;
import com.bstek.dorado.sample.standardlesson.entity.SlDept;

@Component
public class DeptService {
    @Resource
    private SlDeptDao slDeptDao;
    
    @DataProvider
    public Collection<SlDept> getTopDept(){
        return slDeptDao.find("from SlDept where slDept.deptId is null");
    }
    
    @DataProvider
    public Collection<SlDept> getDeptByParentId(Integer parentId){
        if(null != parentId){
            String hql = "from SlDept where slDept.deptId = :deptId";
            Map param = new HashMap();
            param.put("deptId", parentId);
            return slDeptDao.find(hql, param);
        }else{
            return null;
        }
    }
    
    @DataResolver
    @Transactional
    public void saveAll(Collection<SlDept> depts){
        for(SlDept dept:depts){
            slDeptDao.persistEntity(dept);
            Collection<SlDept> childs = dept.getSlDeptSet();
            if(!(childs ==  null)){
                for(SlDept child:childs){
                    //维护关联关系
                    child.setSlDept(dept);
                }
                slDeptDao.persistEntities(childs);
                saveAll(childs);
            }
        }
    }
}

我们仔细观察方法,在此方法我们可以看到通过UpdateAction将depts集合对象传递到后台,然后我们遍历集合上级部门并持久化,获得上级部门的子部门并维护关联关系,由于部门表是递归结构,需要持久化的部门可能是多级结构因此我们需要递归一下,然后持久化部门信息。