Home > Mobile >  I get integrity violation Exception in grails. How to cascade delete to related entity in grails?
I get integrity violation Exception in grails. How to cascade delete to related entity in grails?

Time:05-26

I have a simple eCommerce grails 5 application in which I define CartItem as:

class CartItem {
Customer customer
Product product
Integer quantity}

I have Product class:

class Product {
String name
Double price }

When a product is deleted, cartItem having this product(if any) must also be deleted. (The same also applies to Customer). Right now when I delete product, I get integrity violation exception if there is cartItem with this product.

I am using Hibernate with H2 in-memory database. Without using hibernate configuration (unless this is the only way) how can I achieve product delete cascade to automatic deletion of associate cartItem delete behaviour using grails GORM?

An instance of CartItem is created when a customer adds product to shopping cart.

When a cartItem is deleted (when a product is removed from the shopping cart) nothing happens to the related product or customer. But when a product is deleted its associated cartItem must also be deleted.

CodePudding user response:

CartItem doesn't belong to Product. And therefore Grails cannot delete it when the Product is deleted. But you can take advantage of grails domain class events - "beforeDelete".

https://docs.grails.org/3.0.x/guide/GORM.html#eventsAutoTimestamping

CodePudding user response:

You may not delete Product in this configuration. This is the grails document.

https://docs.grails.org/5.0.0-RC4/ref/Database Mapping/cascade.html

The document shows the example with a hasMany reference.

class Author {
    static hasMany = [books: Book]
    static mapping = {
        books cascade: 'all-delete-orphan'
    }
}

It looks to me that you also need to have hasMany in your CartItem class for this to work looking at the exmaple from the grails document.

You can try to add this line to your CartItem class to see if there is any error saying it cannot find the product reference.

static mapping = {
        product cascade: 'all-delete-orphan'
}

I have not tried this before. So I cannot give you a straight answer.

If this does not work, you will have to roll your own. You can also make changes to the FK index from the database to enable cascade delete. Make sure you document what you did. Otherwise the next guy who picked up the project will be complaining.

  • Related