我有一个带有类的grails项目,当从控制器“手动”执行时,我可以删除没有问题。我使用以下代码。
def delete = {
def projectInstance = Project.get( params.id )
def employee = projectInstance.employee
def projectarray = new ArrayList<Project>();
projectarray += employee.getProjects()
println("Size of projectarray is " + projectarray.size())
if(projectInstance) {
def rolearray = []
projectarray.remove(projectInstance)
def temp = new TreeSet<Project>();
temp += employee.getProjects()
temp.clear()
temp.addAll(projectarray)
employee.projects = temp
projectInstance.employer = null
projectInstance.delete(flush:true)
flash.message = "Project ${params.id} deleted"
redirect(action:"edit", controller: "employee", id: employee.id)
}
else {
flash.message = "Project not found with id ${params.id}"
redirect(action:list)
}
}
这样就可以删除单个实例。
现在我想从不同的控制器中删除员工的所有项目。
这样就存储在员工中:
class Employee implements Comparable
{
static hasMany = [projects:Project]
static constraints =
{
}
static mapping = {
projects cascade:"all-delete-orphan", lazy:false
}
@XmlElementWrapper(name="projectslist")
SortedSet<Project> projects = new TreeSet<Project>(); // make a sortedSet?
}
那么我现在如何从特定员工实例中删除所有项目?
答案 0 :(得分:2)
我可能会误解你的问题,因为我无法理解你的一些代码。这似乎没必要。如果你的关系设置正确(即Project belongsTo Employee),这应该足以删除一个项目:
def delete = {
def projectInstance = Project.get( params.id )
projectInstance.delete(flush:true)
flash.message = "Project ${params.id} deleted"
redirect(action:"edit", controller: "employee", id: employee.id)
}
如果这是一对多,则下次检索员工时项目将会消失。这应该可以删除员工的所有项目:
def delete = {
def employee = Employee.get( params.id )
employee.getProjects().clear()
employee.save(flash:true)
flash.message = "All projects of employee deleted."
redirect(action:"edit", controller: "employee", id: employee.id)
}
假设级联:“all-delete-orphan”。如果情况并非如此,那么您可能还需要删除实例,这可能看起来像这样:
def delete = {
def employee = Employee.get( params.id )
// Make copy to avoid concurrent modification issues later
def copy = new TreeSet<Project>(employee.getProjects());
employee.getProjects().clear();
employee.save(flash:true)
copy.each{
$it.delete();
}
flash.message = "All projects of employee deleted."
redirect(action:"edit", controller: "employee", id: employee.id)
}
我不是一个时髦的专家,所以不确定是否需要副本,或者你是否可以直接迭代集合。似乎总是有一种更加时髦的做事方式。您可能还想查看deleteFrom动态域类方法。根据要删除的关系数量,这可能是一种更有效的grails方法。
答案 1 :(得分:1)
您可以使用Grails在声明hasMany关系时生成的removeFrom*方法 - 它等同于addTo*方法:
def employee = Employee.get(params.id)
employee.projects.toList().each { employee.removeFromProjects(it) } // toList() prevents a ConcurrentModifactionException