How best to deal with MQTT sensor name changing after battery change

I have a number of “cheap” 433MHz temperature & humidity sensors that I track using a LILYGO® LoRa32 V2.1 ESP32 SX1278 (433MHz) board to detect and decode the 433MHz signals and then use MQTT to auto-discover and publish the corresponding topics.

However, when I change the battery in the sensor, the sensor seems to pick a random (new) ID which results in a new MQTT topic and more importantly, a new sensor name.

I have somewhat and painfully managed to “fix” this manually by manipulating the SQLite DB and modifying various files in /homeassistant/.storage that reference the sensor.

However, this is all painful, kludgy and likely brittle as it would be easy to make a mistake…

Is there a better (and ideally automated) way to handle battery changes that would allow me to continue to use the old sensor name without losing any of the history data. or requiring changes to various scripts and automations that reference the old sensor name.

Change the entity_id back to what it was before.

But I want to have the same ‘metadata_id’ since I have othe SQLITE scripts outside of HomeAssistant that for example reference the ‘statistics’ or ‘states’ table. And I don’t want to constantly have to join the ‘statistics_meta’ and ‘states_meta’ tables to select sensors.

So I would like the sensor to have the same ‘metadata_id’ rather than adding more and more sensors each time the battery is chamged.