1

I started learning Elasticsearch recently, have watched already a couple of videos about this technology and noticed that we mark fields in the method’s parameters as final. Simultaneously, we don’t mark parameters with this keyword when use MySQL, for the instance.

Why? Because there are no field locks and transactions inside of Elasticsearch unlike MySQL?

For example:

Let’s suppose that we have a REST controller for users in our app and a method that return user based on its id inside of this controller.

In the case when we use MySQL:

@GetMapping(“/user/{id}”)
public User getUserById(@ParhVariable Long id) {
return userRepository.getById(id).orElse(null);
}

In the case when we use Elasticsearch:

@GetMapping(“/user/{id}”)
public User getUserById(@ParhVariable final Long id) {
return userRepository.getById(id).orElse(null);
}
Serhii Chernikov
  • 353
  • 2
  • 11

1 Answers1

0

It is not connected to ElasticSearch or MySQL. When you set final keyword to your id variable - you just can't assign a new value (an object in case of Long) to this variable inside your getUserById method.

It prevents such situations:

@GetMapping(“/user/{id}”)
public User getUserById(@ParhVariable Long id) {
    id = 10L; // new value
    return userRepository.getById(id).orElse(null); // will response with wrong entity
}

In code above the program will NOT return the value, which user expected. And if you set final keyword on id variable and try to assign new value to id - the program will not even compile, which prevents not expected behavior in runtime.

There is no strict rules always to use final or not - the most common approach is to use final when code is long and complicated.

Check also this answer.

Egor
  • 523
  • 4
  • 15