Nathan the prophet comes to David and tells him an metaphorical story to make him realize his bad deeds
There were two men, one rich and one poor. The rich man had very large flocks and herds, but the poor man had only one little lamb that he had bought. He tended it and it grew up together with him and his children: it was like his child.
I stand guilty before the LORD!
One day, a traveler came to the rich man, but instead of take anything from his own flocks or herds to prepare a meal for the guest, he took the poor man’s lamb and prepared it for his guest.
David flew into a rage and tells Nathan that he deserves to die for what he did. And Nathan said to David, “That man is you! You have put Uriah the Hittite to the sword; you took his wife and made her your wife and had him killed by the sword of the Ammonites."
I stand guilty before the LORD!” And Nathan tells David that Hashem has remitted his sin; and he won't die, However since he has done a bad deed, even his child about to be born will die.
Batsheva's baby becomes sick and David fasts for him and prays to god for him to live. He dies and David stops with his mourning actions. Batsheva becomes pregnant again and bears Solomon and he was favored in Hashem's eyes.