Grails 防止重复插入

标签 grails groovy grails-orm

如何防止域类的重复插入?

Locations location = Locations.findByLocationXY(locationxy)
       if (location == null)
        {

            LocationManagement lm = new LocationManagement()
            location = lm.getSingaporeLocation(locationxy)
            location.save(flush:true)
        }

class Locations {

int id
String locationName
String locationXY

static constraints = {
    id(blank:false, unique:true)
    locationName (blank:false)
    locationXY (blank:false, unique:true)
}
def afterInsert = {

id= this.id
locationName = this.locationName
locationXY = this.locationXY
}

最佳答案

您必须让 Grails 处理这个问题 - 如果您以正确的方式定义约束,则不需要额外的代码。

正如我所见,您已经拥有了

locationXY (blank:false, unique:true)

因此,从我从代码中读到的内容来看,应该不可能插入具有相同 locationXY 的另一个位置。

运行代码后您检查过数据库的内容吗?您的表格中真的有两行具有相同的 locationXY 吗?

顺便说一句:你的线路

location.save(flush:true)

不会抛出异常,因为您没有指定failOnError:true。因此,以下行可能会产生您所期望的结果:

location.save(flush:true, failOnError:true)

PS:您的 afterInsert 代码是做什么用的?为了清楚起见,我只是将其删除。

关于Grails 防止重复插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10967807/

相关文章:

jenkins - 从 Jenkins 中的参数创建环境变量

更新(使用新对象)列表时,Grails 代码失败,但没有找到匹配的编辑器或转换策略

grails - 如何测试从HTTP session 检索信息的Grails服务

grails - 使用geb进行功能测试的依赖性

jenkins - 从 jenkinsfile 执行 groovy 脚本时出现异常 groovy.lang.MissingPropertyException : No such property: args for class: groovy. lang.Binding

groovy - SoapUI:使用 Run TestCase 测试步骤未在上下文中传递

grails - 一个 Grails 域类中的多个多对多关联

java - 在命令对象中绑定(bind)集合时出错

javascript - 输入类型 ="date"在 Bootstrap 模式下不起作用

hibernate - 为什么在Grails中使用此Spock规范会导致 'identifier of an instance of projectname.Event was altered from 1 to 2;'?