How can I add entity base field with unique constraint if some entities already exist? The issue is that adding a base field to a custom entity type in code would result in an issue of unique constraint violation as there does not seem to be a way to preset the value to the newly added field.

setInitialValue() would set the same value for all the existing entities triggering a constraint violation.

setInitialValueFromField() would not do any good as it would only allow fetching value from fields of same type. Otherwise it would be possible to utilise the value from an ID field and then replace those initial values with something more suitable.

Is there any meaningful way for doing that?
I think you'd need to write an update hook to first add you new base field via the EntityDefinitionUpdateManager (an example here since automated entity updates were removed.)

function example_update_8701() {
  // Add the unique constraint, etc.
  $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $field_storage_definition = $entity_definition_update_manager-&gt;getFieldStorageDefinition('hostname', 'comment');
  $field_storage_definition-&gt;setDefaultValueCallback(Comment::class . '::getDefaultHostname');
  $entity_definition_update_manager-&gt;updateFieldStorageDefinition($field_storage_definition);
}


Then in a post_update hook, you would load each entity and populate the new field with values in whatever manner makes sense and re-save.

The two methods mentioned in your question shouldn't be called since you're updating the existing entities rather than creating new ones.