Question

I have two domain objects

Class Attachment{
    static hasMany = [mailDrafts: MailDraft];
}

Class MailDraft{
  static hasMany = [attachments: Attachment]
   static belongsTo = Attachment
} 

It has created the three tables

1)attachment
2)mail_draft 
3)attachment_mail_drafts

attachment_mail_drafts: id, mail_draft_id

Now, I wnat to write a a HQL query to delete an entry from the table 'attachment_mail_drafts' where 'attachment_id' is 4, So what is the query.

Was it helpful?

Solution

You can't do this with HQL, you can read more why here. Instead you would do the following:

def a = Attachment.get(4)
a.mailDrafts.clear()
a.save()

OTHER TIPS

It seems that in HQL you can only remove objects, removing associations is not possible. You could use raw SQL or use GORM method removeFrom:

def attachment = Attachment.get(1)
def mailDraft = attachment.mailDrafts.find { it.id = 4 }
attachment.removeFromMailDrafts(mailDraft).save(flush: true)

You could implement the m:n collections avoiding the hasMany/belongsTo technique using the approach explained by Mr Burt Beckwith, this improves the performance and can help you to safely delete the 'attachment_mail_drafts' entity that you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top