2

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

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
}
4

2 回答 2

4

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

正如我所看到的,你已经有了一个

locationXY (blank:false, unique:true)

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

运行代码后,您检查过数据库的内容吗?你真的在你的桌子上有两条线locationXY吗?

顺便说一句:你的线

location.save(flush:true)

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

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

PS:你的afterInsert代码是干什么用的?为了清楚起见,我会删除它。

于 2012-06-10T19:45:33.880 回答
0

您不需要为 id 添加约束。这是由 grails 自动完成的。我认为如果您删除它,程序应该按您的预期执行。唯一的唯一值是 locationXY。

于 2012-06-10T14:03:37.577 回答