2012-03-24 42 views
1

我有以下設置。域驗證,但不會保存

類,例如,有CarPart(belongsTo = [car:Car])的汽車。

當我創建一個租車我也想創建索姆默認CarParts,所以我做

def car = new Car(bla bla bla) 
def part = new CarPart(car:car) 

現在,當我做car.validate()或part.validate()似乎罰款。 但是當我做,如果(car.save & & part.save()我得到這個異常:?

2012-03-24 14:02:21,943 [http-8080-4] ERROR util.JDBCExceptionReporter - Batch entry 0 insert into car_part (version, car_id, id) values ('0', '297', '298') was aborted. Call getNextException to see the cause. 
2012-03-24 14:02:21,943 [http-8080-4] ERROR util.JDBCExceptionReporter - ERROR: value too long for type character varying(6) 
2012-03-24 14:02:21,943 [http-8080-4] ERROR events.PatchedDefaultFlushEventListener - Could not synchronize database state with session 
org.hibernate.exception.DataException: Could not execute JDBC batch update 

Stacktrace follows: 
java.sql.BatchUpdateException: Batch entry 0 insert into car_part (version, deal_id, id) values ('0', '297', '298') was aborted. Call getNextException to see the cause. 
    at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2621) 
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1837) 
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:407) 
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2754) 
    at $Proxy20.flush(Unknown Source) 
    at ristretto.DealController$_closure5.doCall(DealController.groovy:109) 
    at ristretto.DealController$_closure5.doCall(DealController.groovy) 
    at java.lang.Thread.run(Thread.java:722) 

任何想法

回答

2

呼叫驗證真的只是要檢查約束什麼是失敗的您保存的是實際的持久化到數據庫(生效並不能真正檢查)

一般來說,Grails的,你會想這樣做2的這1方式:

def car = new Car(bla bla) 
car.save() 
def carPart = new CarPart(car:car) 
carPart.save() 

def car = new Car(bla bla) 
def carPart = new CarPart(bla bla) 
car.addToCarParts(carPart) 
car.save() 
+0

很好的回答,但我真的想用某種類型的交易要做到這一點,如果由於某種原因,CarPart不保存任何一方都不應該在車... – marko 2012-03-25 13:57:28

+0

所以把它放在一個服務和交易將得到處理。如果是這種情況,我的第二個例子會更好。如果CarPart失敗,錯誤將持續到Car並且事務將被回滾。 – Gregg 2012-03-26 03:14:57

+0

我試着在服務中做到這一點,我得到我的車(已經創建),並做CarPart p = new CarPart(bla bla bla).save(),它給我:java.sql.BatchUpdateException:批次條目0插入('0','2012-03-26 23:11:01.512000 +02:00:00','303','SHAFT','368')的car_part(version,created,car_id,status,id)被中止。調用getNextException來查看原因。 \t at org.postgresql.jdbc2.AbstractJdbc2Statement $ BatchResultHandler.handleError(AbstractJdbc2Statement.java:2621) – marko 2012-03-27 07:12:54