Issue
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?
Solution
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.
int id = newQuoteRepository.findByTitle(data.getTitle()).size();
if (id > 0) {
data.setCounter(data.getCounter() + 1);
// persist it
}
// Show title:
System.out.println(data.getTitle() + " " + data.getCounter());
There are several advantages to this approach.
- You work with numbers directly
- No need to do some
String
magic to achieve what you want - Cleaner
Answered By - Renis1235
Answer Checked By - Willingham (JavaFixing Volunteer)