Results 1 to 2 of 2

Thread: unidirectional one-to-one non-cascade delete

  1. #1
    Join Date
    Jul 2010
    Posts
    16

    Default unidirectional one-to-one non-cascade delete

    I have a simple 1-1 unidirectional relationship ..
    class BulkEmail {
    ...
    Template template
    }
    class Template {
    ...
    }
    so a single template can be used by a bunch of BulkEmails .. problem is when I try to delete the template which is being used by multiple bulkemails i am getting this error

    2010-08-30 22:41:11,812 [http-8080-1] ERROR util.JDBCExceptionReporter - Integrity constraint violation FKDE7C6A2F88075EF9 table: BULK_EMAIL in statement [delete from template where id=? and version=?]
    2010-08-30 22:41:11,812 [http-8080-1] ERROR events.PatchedDefaultFlushEventListener - Could not synchronize database state with session
    org.hibernate.exception.ConstraintViolationExcepti on: could not delete: [beam.Template#1]

    It makes sense why grails isnt able to do it .. it cant delete the template because its still being references by the BulkEmail objects .. I tried changing my code to something like this

    BulkEmail.findAllByTemplate(templateInstance).each {
    it.template.delete()
    }
    templateInstance.delete(flush: true)

    this also doesnt works .. how can I delete a template while removing its referencing from all objects using it

    Thanks
    Adeel

  2. #2
    Join Date
    Jun 2010
    Location
    London
    Posts
    304

    Default

    Do you want the BulkEmails to remain after you have deleted the Template? I'm not sure it's particularly common, but you can do it by adding a nullable: true constraint to BulkEmail:

    Code:
    class BulkEmail {
        Template template
    
        static constraints = {
            template nullable: true
        }
    }
    Before you delete the template, you have to nullify all references to it:

    Code:
    def template = Template.get(templateId)
    BulkEmail.findAllByTemplate(template).each { it.template = null }
    template.delete()
    You could also add a hasMany in Template and use the removeFrom() method instead. It's up to you.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •