@Override
public List<Tag> createTags(Set<String> tagNames) {
List<Tag> existingTags = tagRepository.findByNameIn(tagNames);
Set<String> existingTagNames = existingTags.stream()
.map(Tag::getName)
.collect(Collectors.toSet());
List<Tag> newTags = tagNames.stream()
.filter(name -> !existingTagNames.contains(name))
.map(name -> Tag.builder()
.name(name)
.posts(new HashSet<>())
.build())
.collect(Collectors.toList());
List<Tag> savedTags = new ArrayList<>();
if(!newTags.isEmpty()) {
tagRepository.saveAll(newTags);
}
savedTags.addAll(existingTags);
return savedTags;
}```
my question was that when i do tagrepo.saveAll(new tags)
the new tags get added to the repo yes, but when i do savedTags.addAll(existingTags), do the new tags also come into the existingTags because of some context update?
#question regarding my service
1 messages · Page 1 of 1 (latest)
<@&1004656351647117403> please have a look, thanks.
No.
savedTags is just a list you created and you put the existingTags in it from a previous repo call. No magic happening.
@Transactional
public List<Tag> createTags(List<String> tagNames) {
Set<String> names = new HashSet<>(tagNames);
List<Tag> existing = tagRepository.findByNameIn(names);
names.removeAll(
existing.stream()
.map(Tag::getName)
.toList()
);
List<Tag> created = tagRepository.saveAll(
names.stream()
.map(Tag::new)
.toList()
);
return Stream.concat(existing.stream(), created.stream()).toList();
}
There's probably a lot of ways to skin the cat.