I would like to know what good practice is in the following situation:
@Entity
@Table(name = "word")
class WordEntity(uuid: UUID? = null,
@Column(nullable = false, unique = true) val name: String
) : BaseEntity(uuid)
If i have an Iterable of this entity and want to call the method saveAll to persist it to the database a ConstraintViolationException can be thrown.
So my goal is to add only unique records to the database. I can loop and do something like this:
fun saveAll(words: List<WordRequest>): List<WordDTO> {
...
for (wordEntity in wordEntities) {
try {
result.add(wordRepository.save(wordEntity))
} catch (e: RuntimeException) { }
}
...
}
OR i can do a findByName on every loop to check if it exists or not.
So my question is which option should i go for and is there a better way to handle this?