I am currently working with a PostgreSQL database, Spring and Hibernate. I have one table where attribute correlation_id is unique. Each time before I add a new element first I have to check does any item with a new correlation_id already exist in db or not.
For this case I have implemented recursive function that will generate a new correlation_id and check does it exist or not in db. It means this function will make a call on db each time so sometimes it can be just one call but sometimes i could be five, ten or even more. This example is shown in example one.
Example1:
private String generateId() {
String myId = StaticFunction.generateMyId();
MyMessages doesExist = MyServiceDaoImpl.checkDoesItExistInDB(myId);
if(doesExist != null) {
generateId();
}
return myId;
}
In the second example I suppose that I could create just one call to db and retrieve all items and put them into collection. Then I am able to via stream to search for specific item using also recursive function. Example2:
private String generateId(List<MyMessages> messages) {
String myId = StaticFunction.generateMyId();
MyMessages myMessage = messages.stream().filter(m ->
m.getCorrelationId.equals(myId)).findFirst().orElse(null);
if (MyMessages != null) {
generateId(messages);
}
return myId;
}
My question is whats is the best approach to make this thing right? Do you have some other solutions? What are the advantages and disadvantages of above examples?