2010-08-12 116 views
0
public class Room { 
    static belongsTo = [hotel:Hotel] 
    Source source 
    long sourceid 
    RoomType type 
    float price 
    float oldPrice 
    Currency currency 
    boolean isShown = false 
    boolean approved = false 
    static hasMany = [roomTexts:RoomText] 

    def beforeDelete() { 
    Photos.withNewSession { 
     Photos.findAllByRoom(this).each {photosInstance-> 
     photosInstance.delete() 
     } 
    } 

    RoomFeatures.withNewSession { 
     RoomFeatures.findAllByRoom(this).each {roomF-> 
     roomF.delete() 
     } 
    } 
    } 

} 



然後:
的Grails:級聯刪除鍵和外鍵

def room = Room.get(1) 
room.delete() 

將拋出com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException。

Cannot delete or update a parent row: a foreign key constraint fails (`prod_test`.`photos`, CONSTRAINT `FKC50C8881EC5F6358` FOREIGN KEY (`room_id`) REFERENCES `room` (`id`)) 

這是因爲照片刪除會話尚未刷新到DB和Hibernate試圖刪除房單位,我想......

這裏是房間刪除代碼:

Room.withTransaction{status-> 
    roomInstance.delete(flush: true) 
} 

有沒有解決此問題的解決方法或「正確方法」?
當然,我可以在刪除房間之前手動刪除所有照片,但使用beforeDelete有助於保持代碼清潔並避免代碼重複。

回答

2

爲什麼在hasMany列表中沒有照片和RoomText,並且照片屬於Room?

0

如果照片歸房間所有,則不必事先將其刪除。只要刪除房間和照片去吧?雖然我沒有看到「照片」和「房間」之間的關係,但如果您發佈Photo類,它可能會更清晰。