As part of R2DBC learning process, i have a complex scenario of creating related entities as part of creating main entities. I am trying to create a Film entity and its related entities.
My request is something like this
{
"title" : "Star Wars: The Rise Of Skywalker",
"description": "In the riveting conclusion of the landmark Skywalker saga, new legends will be born-and the final battle for freedom is yet to come.",
"releaseYear": "2019",
"language": "English",
"rentalDuration": 7,
"rentalRate": "4.99",
"length": 165,
"replacementCost": "14.99",
"rating": "PG",
"specialFeaturesList": [ "SciFi", "Star Wars"],
"filmCategory": "Sci-Fi",
"actors":[
{
"firstName":"Daisy",
"lastName": "Ridley"
},
{
"firstName":"Carrie",
"lastName":"Fisher"
},
{
"firstName": "Oscar",
"lastName": "Isaac"
},
{
"firstName": "Adam",
"lastName": "Driver"
},
{
"firstName": "Mark",
"lastName": "Hamill"
},
{
"firstName": "John",
"lastName": "Boyega"
}
]
}
And below is my logic and code
/**
* Logic :
* Transaction start
* -- find Language or insert
* -- find Flim by (Title,release year and languageId) or insert
* -- foreach( actor)
* ---- find or create actor
* ---- find or create film_actor ( film id, actor)
* -- end
* -- for category
* ---- find category or insert
* ---- find film_category or insert
* -- end
* -- Map data
* Transaction end
*
* @param filmRequest
* @return Mono<Pair < Boolean, FilmModel>>
*/
Code :
@Override
public Mono<Pair<Boolean, FilmModel>> create(FilmRequest filmRequest) {
return Mono.just(filmRequest)
.flatMap(this::getOrCreateLanguage)
.flatMap(languageInput -> getOrCreateFilm(filmRequest, languageInput.getLanguageId()))
.flatMap(filmInput ->
Mono.zip(Mono.just(filmInput),
Flux.fromIterable(filmRequest.getActors())
.flatMap(this::getOrCreateActor)
.doOnNext(actorInput -> getOrCreateFilmActor(filmInput.getSecond().getFilmId(), actorInput.getActorId()))
.collectList(),
Mono.just(filmRequest.getFilmCategory())
.flatMap(this::getOrCreateCategory)
.flatMap(category -> getOrCreateFilmCategory(filmInput.getSecond().getFilmId(), category.getCategoryId()))
))
.map(tuple -> {
FilmModel filmModel = GenericMapper.INSTANCE.filmToFilmModel(tuple.getT1().getSecond());
List<ActorModel> actorModelList = tuple.getT2().stream().map(GenericMapper.INSTANCE::actorToActorModel).collect(Collectors.toList());
filmModel.setActors(actorModelList);
return Pair.of(tuple.getT1().getFirst(), filmModel);
}).as(operator::transactional);
}
And this is the failure I am getting:
TransientDataAccessResourceException: Failed to update table [film_category]. Row with Id [1006] does not exist.
https://gist.github.com/harryalto/d91e653ca1054038b766169142737f87
The Film entity ID is not persisted and because of which the dependent insert is failing.