"The operation is over. It was highly successful. We have rescued the hostages in such a large number," chief military spokesman Major General Athar Abbas told state-run PTV.
"42 hostages were rescued in the first phase and five more were rescued later. The situation is now totally under control.... The entire area has been cleared. There are no terrorists inside," he said.
Major General Abbas said the commandos killed four terrorists, including some who were wearing suicide jackets. He said three of hostages also died during the operation.
The development came a day after a group of terrorists armed with assault rifles and grenades launched an audacious attack on the army's General Headquarters in Rawalpindi near here and took several security personnel hostage. Four of the attackers and six security personnel were killed on Saturday.
Troops were conducting mopping up operations to check the presence of other terrorists in the area.
Soon after the attack on Saturday, Tehrik-e-Taliban Pakistan claimed responsibility for it.