【发布时间】:2014-09-08 22:58:17
【问题描述】:
问题:
我有“路由”域,它有站点(域)。
如果我保存路线,我也应该保存站点。 (使用级联:'all' 映射)
但是,如果数据库中已经存在同名的站,我想使用它,不再创建这样的站。
所以我保存的路线必须只保存新站点。
示例:
域名:
class Route {
String name
List<Station> stations
static mapping = {
stations cascade: 'all', lazy: false
}
static hasMany = [
stations: Station
]
}
class Station {
String name
}
控制器/服务:
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)”
但是我的项目足够大,可以在代码中测试这些东西。
是否可以在域中的某个地方定义它?或任何其他解决方案?
【问题讨论】:
-
你能发布你的代码吗?
-
已添加。但在这个问题中,我只想知道“如何”的最佳实践和可能的解决方案。
标签: grails grails-orm