Grails的唯一复合键问题(Grails unique compound key issues)

2019-10-24 12:15发布

给定一个GORM类:

    class PriceSheet {

    Client client
    Population population
    Product product
    RevenueModelType modelType

    BigDecimal price

    static constraints = {
        client(unique: ['population', 'product', 'modelType'])
    }
}

我想要一个PriceSheet要保存/只有在客户端,人口,产品和modelType是唯一的更新。 (应该只有客户端,人口,产品和modelType的组合中的一个pricesheet项目)。

关键是在MySQL的创建。

我的问题是验证通过Grails的,而保存失败。

    priceSheetInstance.validate()

    if (priceSheetInstance.hasErrors()) {
        respond priceSheetInstance.errors, view:'create'
        return
    }

    priceSheetInstance.save flush:true

任何意见或建议? 我把调试器在断点处验证后,看看错误都是空的。

Grails的2.3.10

Answer 1:

首先,你需要告诉GORM的属性让你的复合主键,然后你的域类需要实现Serializable接口。 最终的结果是这样的:

import org.apache.commons.lang.builder.HashCodeBuilder

class PriceSheet implements Serializable {
    Client client
    Population population
    Product product
    RevenueModelType modelType

    BigDecimal price

    static constraints = {        
    }

    static mapping = {
        id composite: ['client', 'population', 'product', 'modelType']
    }

    boolean equals(other) {
        if(!(other instanceof PriceSheet)) return false
        other.client == client && other.population == population && other.product == product && other.modelType == modelType
    }

    int hashCode() {
        def builder = new HashCodeBuilder()

        builder.with {
            append client
            append population
            append product
            append modelType
        }

        builder.toHashCode()
    }    
}

你可以阅读更多关于格姆组合键在这里 。



Answer 2:

最终的解决方案是在控制器包装withNewSession为节省:

    PriceSheet.withNewSession {

        priceSheetInstance.validate()

        // needed to call save in order to check the unique compound key
        // validate alone wasn't working
        // also needed to wrap withNewSession above
        // PriceSheet GORM object implements Serializable as well
        // spent way more time than expected on this.... wrestled with Grails

        if (priceSheetInstance.hasErrors() || (priceSheetInstance.save(failOnError: true) && priceSheetInstance.hasErrors())) {
            respond priceSheetInstance.errors, view:'create'
            return
        }

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'priceSheet.label', default: 'Price Sheet'), priceSheetInstance?.id])
                redirect (action: 'index')
            }
            '*' { respond priceSheetInstance, [status: CREATED] }
        }
    }

我没有包裹withNewSession更新...其实,包装withNewSession更新是造成StaleObjectExceptions



文章来源: Grails unique compound key issues
标签: grails gorm