Martinez, 37, had promised champion Chavez a beating and he was true to his word for much of the fight as he dominated with his quicker, busier style.
He bloodied his opponents' nose and closed his left eye with southpaw right jabs and straight left hands, and gradually weakened him with left hands to the body.
However, Chavez landed a series of left hooks early in the final round and knocked Martinez down.
The challenger was badly hurt but he returned fire and managed to hang on until the bell to inflict a first defeat on the 26-year-old Mexican.
"Julio fought a great fight. He showed he had heart right until the end," said Martinez, whose record is now 50-2-2.
Chavez said: "I was 20 seconds away from knocking him out. I started way too late. Going into the fight, I thought I was going to be able to do all night what I did in that final round. A rematch is justified."