gpt4 book ai didi

grails - grails:不要再次保存类似的域对象,请使用当前对象

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

问题:
我有“路线”域,其中有车站(域)。
如果我保存路线,我也应该保存车站。 (使用级联:“全部”映射)
但是,如果数据库中已经存在具有相同名称的工作站,那么我想使用它,并且不再创建此类工作站。
因此,我保存的路线只能保存新的车站。

例:
域:

class Route {
String name
List<Station> stations

static mapping = {
stations cascade: 'all', lazy: false
}
static hasMany = [
stations: Station
]
}

class Station {
String name
}

Controller /服务:
def route = new Route()
route.stations.add(new Station("stationOne"))
route.stations.add(new Station("stationTwo"))
route.save()
//now in db there are 2 stations.

//now create new route with 2 stations, with one similar to already saved ('stationOne').
def route2 = new Route()
route2.stations.add(new Station("stationOne")) //<-- this one i want to be replaced
// with the inDB one, if i save the route
// in DB must be only one "stationOne"
// and every route must point to it,
// not own "stationOne", if the route saved
route2.stations.add(new Station("stationThree"))

route2.save()
//now i wish in DB there are only 3 stations.
//and route2 has both from DB. And the reference (in list) from route2 to "stationOne"
//inMemory object is now replaced with reference to inDB station object.

我可以编写代码,例如“replaceWithDBStationReferences(route)”
但是我的项目足够大,可以在代码中测试这些东西。
是否可以在域中的某处定义它?或其他解决方案?

最佳答案

您可以使用 findOrCreate 动态方法:

route2.stations.add(Station.findOrCreateByName("stationOne"))
findOrCreateByNamefindByName相似,不同之处在于,如果普通查找程序将返回null(如果未找到任何内容),则 findOrCreate将基于查询参数(在这种情况下为 new Station(name:'stationOne'))创建一个新的瞬时实例。

还有 findOrSaveBy... 可以执行相同的操作,但是在返回新实例之前也要保存它。

关于grails - grails:不要再次保存类似的域对象,请使用当前对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25734313/

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