In my database, I am searching for a specific value. If that value does not exist, it should simply be added, but if it exists, a counter should be added next to it.
So for instance, if the value Hello World already exists, the added value should be Hello World 1, the next one should be Hello World 2 and so on…
This is what I have tried:
int id = newQuoteRepository.findByTitle(data.getTitle()).size();
System.out.println(id);
if (id > 0) {
data.setTitle(data.getTitle() + id);
}
Well, basically it works but it is not really what I want. So if a value is bar
, it will add bar1
. And next time, it will add bar1
again, because it is searching for bar
and so the added value, which was bar1
, will be ignored.
So this is what I have: bar, bar1, bar1, bar1 …
And this is how it should be: bar, bar1, bar2, bar3 …
What could be a solution for this issue?
2
Answers
You can use
findByTitleLike
instead offindByTitle
for your task.It will find titles match with the given regex.One way to solve this would be to add a
counter
column to your table and whenever you need to show your title, concatenate the title with this counter.e.g.
There are several advantages to this approach.
String
magic to achieve what you want