我有一些奇怪的行为,我的对象图中的保存级别不正确。也许它与嵌套事务有关,但可能没有。
以下是我的3个域类:
Station.groovy
class Station {
/** Dependency injected {@link de.hutapp.tapandknow.system.SettingsService}.*/
def settingsService
static hasMany = [localizedStations: LocalizedStation,
stationIdentifiers: AbstractStationIdentifier]
}
LocalizedStation.groovy
class LocalizedStation {
/** Delete-cascade from the {@link Station} parent. */
static belongsTo = [station : Station]
/** An image that represents the LocalizedStation. */
MediaFile headerImage
/** The articles inside this LocalizedStation .*/
List<Article> articles
static hasMany = [articles: Article]
static mapping = {
headerImage cascade: 'all'
articles cascade: 'all-delete-orphan'
}
}
MediaFile.groovy
class MediaFile {
/* some basic properties here*/
static constraints = {
name blank: false
originalFilename blank: false
description blank: false
}
def beforeDelete() {
// delete the associated file
new File(getFileLocation()).delete()
}
}
因此对象图是Station-&gt; LocalizedStation-&gt; MediaFile
我使用以下服务方法保存/更新对象:
StationService.groovy
@Transactional
class StationService {
def mediaFileService
/**
* Creates a new {@link Station} and saves it.
* @return The newly created {@link Station} instance.
*/
Station createStation(LocalizedStation localizedStationInstance, InputStream headerImage, String originalFilename) {
localizedStationInstance = updateLocalizedStation(localizedStationInstance, headerImage, originalFilename)
Station stationInstance = new Station()
stationInstance.addToLocalizedStations(localizedStationInstance)
stationInstance.save()
stationInstance.localizedStations[0].headerImage.save() // TODO: check why this is necessary
return stationInstance
}
LocalizedStation updateLocalizedStation(LocalizedStation localizedStationInstance, InputStream headerSource, String originalFilename) {
if (headerSource) {
MediaFile headerFile = mediaFileService.createMediaFile(headerSource, originalFilename, "foobar") // TODO: add description
localizedStationInstance.headerImage = headerFile
}
localizedStationInstance.save()
return localizedStationInstance
}
}
MediaFileService.groovy
@Transactional
class MediaFileService {
MediaFile createMediaFile(InputStream input, String originalFilename, String description) {
MediaFile mediaFileInstance = new MediaFile(
name: originalFilename,
description: description)
mediaFileInstance.save(flush: true) // flush for id
mediaFileInstance.storeMediaFile(input, originalFilename)
mediaFileInstance.save()
return mediaFileInstance
}
}
如您所见,如果我调用stationService.createStation(),我必须手动保存挂在LocalizedStation上的MediaFile。只有在我调用createStation()时才会发生这种情况,而createStation()本身调用的是updateLocalizedStation()。 然后,除非我在createStation()中明确保存,否则不会保留MediaFile。
如果我直接调用updateLocalizedStation(),一切都按预期工作。
有任何想法或建议吗?
更新:
如果我将@Transactional(propagation = Propagation.REQUIRES_NEW)添加到createMediaFile()方法,这个问题就会消失。
据我了解文档,这会创建一个新事务。但这不是我想要的,我想要一个涵盖所有方法的交易。