skip to Main Content

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


  1. You can use findByTitleLike instead of findByTitle for your task.It will find titles match with the given regex.

    Login or Signup to reply.
  2. 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
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search