我有三個類呈現並且它們連接到鏈的域類結構的特例:事件< - 房間< - 投影儀。 (所有的關係艦是一個一對一)Grails具有belongsTo和默認值的多個域類
實施的樣子:
class Event {
Room room
static constraints = {
room(nullable:false)
}
}
class Room {
Projector projector = new Projector()
static belongsTo = [event: Event]
static constraints = {
projector(nullable:false)
}
}
class Projector {
String something = "Something"
static belongsTo = [room: Room]
static constraints = {
room(nullable:false)
}
}
當我想創建一個新的房間我想到的是,投影機將被默認創建事件:
class TestController {
def index() {
Room room = new Room()
Event event = new Event(room: room)
event.save(flush: true, failOnError: true)
render event
}
}
我收到例外以下
| Error 2012-07-11 16:09:12,541 [http-bio-8080-exec-3] ERROR errors.GrailsExceptionResolver - TransientObjectException occurred when processing request: [GET] /Test/room/index
object references an unsaved transient instance - save the transient instance before flushing: Projector. Stacktrace follows:
Message: object references an unsaved transient instance - save the transient instance before flushing: Projector
Line | Method
->> 46 | onApplicationEvent in org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 18 | index in RoomController
| 1110 | runWorker . . . . in java.util.concurrent.ThreadPoolExecutor
| 603 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . . . . . in java.lang.Thread
看來,級聯超過三類不保存默認值。有沒有解決方案?或者我做錯了什麼?
只是爲了排除故障...如果您將'投影機投影機=新投影機()'改爲'投影機投影機'並將'房間=新房間()'更改爲'房間=新房間(投影機:新的投影儀())'有一些方法可以在域類上進行元編程。這可能是通過直接爲域類中的投影機分配值,您將繞過處理級聯保存的掛鉤。 – proflux 2012-07-11 15:53:17
您的推薦有效。也許我的實現繞過了鉤子,但我應該如何實現這一點...我不想讓其他開發人員創建投影機時想要創建空間和事件。 – kuceram 2012-07-12 08:01:36
不是100%確定這是否可行,但我會嘗試向Room添加構造函數,並在構造函數中放置'this.projector = new Projector()'語句。 – proflux 2012-07-12 12:47:14