Bastianini wins in Emilia-Romagna after final lap showdown with Martin
Marc Marquez finished third for Gresini Racing and with three Ducati bikes on the podium, the Italian manufacturer also clinched the constructors' championship with six rounds to spare.
With Spaniard Martin leading the race on the final lap, Bastianini made an aggressive overtake on turn four that elbowed the Pramac Racing rider out of the way before he took the chequered flag as the home crowd roared in delight.
"Jorge was perfect for all the race and it was too difficult to try to overtake him," Bastianini said after his second race victory of the season.
"In the last lap I saw a bit of space inside turn number four, I entered a bit on the limit but at the end I closed the line... It's incredible to win today here in Misano in front of my friends."
Martin finished second and the result extended his lead over Bagnaia in the riders' championship to 24 points.
Polesitter and sprint winner Bagnaia briefly fell to second when Martin had yet another perfect launch off the line but the Italian immediately took back his place at the head of the pack on the next turn.
However, Martin did not give up and after swapping positions once, he eventually made an overtake stick on the inside, forcing Bagnaia to back off before his teammate Bastianini also moved up as the reigning champion fell to third.
Bagnaia seemed to be having trouble with his pace with slower laps as Martin quickly extended his lead but Bastianini gave chase on his home circuit.
Pedro Acosta had done well to stay in fourth but the Tech3 rookie slid off with 18 laps to go, allowing Marquez to move up to fourth and slot in behind Bagnaia who was clearly struggling to catch up to the lead pack.
With 12 laps left, Bagnaia suddenly lit up the screens when he started setting race lap records and that spurred Martin to also increase his pace when he received the message from the pit wall.
But all the metres Bagnaia ate up to reel in Martin were thrown away when the Italian lost his balance on turn eight, making his landmark 100th MotoGP race one to forget with his third Sunday retirement of the season.
That left Martin to battle it out with just one factory Ducati and Bastianini, who was egged on by the fans, was relentless in his pursuit of the Spaniard who nearly surrendered the lead with three laps left.
But Bastianini's last-lap overtake pushed Martin off the track as the Spaniard slowed down and raised his arm in protest although he eventually accepted the result.
"I just tried to close the gap, I think the manoeuvre maybe was a bit too much because he pushed me out of the track, so I couldn't fight back," Martin said.
"I think I was stronger. I deserve the victory but it's okay. I will try again in the next one."