gpt4 book ai didi

grails - 无法获得级联保存,无法在嵌入式类引用上删除以正常工作

转载 作者:行者123 更新时间:2023-12-02 15:49:24 25 4
gpt4 key购买 nike

我创建了两个简单的Grails V3域类,其中位置是这样嵌入父级场所中的属性类型的

import java.time.LocalDate

class Venue {

String name
LocalDate dateCreated
LocalDate lastVisited
LocalDate lastUpdated
GeoAddress location

static hasOne = [location:GeoAddress]

static embedded =['location']

static constraints = {
lastVisited nullable:true
location nullable:true
}
static mapping = {
location cascade: "all-delete-orphan", lazy:false //eager fetch strategy

}
}


class GeoAddress {

String addressLine1
String addressLine2
String addressLine3
String town
String county
String country = "UK"
String postcode

static belongsTo = Venue

static constraints = {
addressLine1 nullable:true
addressLine2 nullable:true
addressLine3 nullable:true
town nullable:true
county nullable:true
country nullable:true
postcode nullable:true
}
}

但是,当我编写一个集成测试时,我发现位置的级联创建不起作用(在传递到 field 之前,我必须保存该位置不再是临时的。

另外,当我在启用了flush:true的场所运行删除并查询地址时,我仍然获得返回的嵌入式地址-我认为使用flush:true会看到我的GeoAddress级联删除,但是我的测试失败了正如我期望的那样,在使用GeoAddress.get(loc.id)时不会得到null
@Integration
@Rollback
class VenueIntegrationSpec extends Specification {
void "test venue with an address" () {
when: "create a venue and an address using transitive save on embedded "
GeoAddress address = new GeoAddress (addressLine1: "myhouse", town: "Ipswich", county: "suffolk", postcode : "IP4 2TH")
address.save() //have to save first - else Venue save fails

Venue v = new Venue (name: "bistro", location: address)
def result = v.save()

then: "retrieve venue and check its location loaded eagerly "
Venue lookupVenue = Venue.get(v.id)
GeoAddress loc = lookupVenue.location
loc.postcode == "IP4 2TH"
loc.town == "Ipswich"

when: " we delete the venue, it deletes the embedded location (Address)"
v.delete (flush:true)
GeoAddress lookupLoc = GeoAddress.get (loc.id)

then: "address should disppear"
lookupLoc == null
}

我以为我已经正确设置了,但是显然没有。为什么我对Venue.save()和delete()的级联操作不能级联到我的嵌入式位置(GeoAddress)条目?

最佳答案

如果我正确理解
cascade: "all-delete-orphan"
仅当您有hasMany=[something:Something]时才需要

在您的情况下,如果我要创建这样的关系,则hasOneGeoAddress location可能是更好的设置。我知道两者之间会有细微的差异。

无论如何,您都在进行理论上的测试。我认为您需要捕获错误才能开始弄清楚为什么它没有将预期的行为串联起来。所以要么

if (!v.delete(flush:true) { 
println "--- ${v.errors}"
}

或包起来

try catch block



。我对hasMany关系有一个类似的问题,这是由于底层hasMany表关系本身的设置而导致与其他表共享记录。技巧是仅从对象本身中删除条目:
lookupVenue .removeFromLocation(loc)
正如我所说的,这是一个hasMany关系

关于grails - 无法获得级联保存,无法在嵌入式类引用上删除以正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42054344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com