Reputation: 282
I'm having a problem right now, I have 2 domain classes namely Doctor and Patient, where they have a 1:m relationship. here's my code for class Doctor
class Doctor {
String name
String specialization
def doctorService
static hasMany = [patients: Patient]
static belongsTo = [hospital: Hospital]
static constraints = {
name(blank:false)
specialization(blank:false)
patients(nullable:true)
hospital(nullable:false)
}
String toString(){
"Doctor ${name} "
}
}
-->and here's my code for class Patient:
class Patient {
String name
String ailment
int age
Date dateAdmit, dateDischarge
static belongsTo = [doctor: Doctor, hospital: Hospital]
static constraints = {
name(blank:false, maxSize:100)
ailment(blank:false)
age(size:1..200)
dateAdmit(nullable:true)
dateDischarge(nullable:true)
hospital(nullable:false)
doctor(nullable:false, validator:{val, obj -> val.hospital == obj.hospital})
}
String toString(){
"${name} "
}
}
-->
I wanted to delete a doctor who doesn't have a patient using executeUpdate(). I can select the doctors without patients using dynamic finders like this.
_
def d = Doctor.findAll("from Doctor as d where not exists" +
"(from Patient as p where p.doctor = d)")
_
seems like that syntax doesn't work in executeUpdate(), Im just a newbie in grails. please help me.. thanks...
Upvotes: 1
Views: 3971
Reputation: 75671
Use this:
Doctor.executeUpdate('delete from Doctor d where d.patients is empty')
Upvotes: 10
Reputation: 1846
You can also do:
def d = Doctor.findAll("from Doctor as d where not exists" + "(from Patient as p where p.doctor = d)")*.delete()
Upvotes: -1
Reputation: 10094
Have you tried to use the Hibernate Criteria Builder ?
Much more flexible and maintainable than executeUpdate()
Doctor.withCriteria{
isEmpty patients
}.each{it.delete()}
WARNING : this code is not tested. Do not use in production without testing :-D
But that's the idea
Upvotes: -2