如何防止域类的重复插入?
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/