The 27-year-old right-hander has been one of the most effective relievers in baseball since joining the Diamondbacks to pitch in front of closer J.J. Putz. Hernandez would've been arbitration eligible after this season.
Arizona announced the deal after beating the Chicago Cubs 5-1 Sunday.
Hernandez is 0-1 with two saves and a 2.90 ERA this season, with 45 strikeouts in 31 innings over 33 games. On Friday against the Cubs, he became the first Arizona player with a hit and a save in the same game since Jose Valverde in 2003.
Last season, Hernandez set career-highs with 11 saves, 74 games and 77 strikeouts, serving as Arizona's closer for a short time when Putz went on the disabled list.
He is 17-22 with 15 saves and a 4.32 ERA in four seasons with Baltimore and Arizona.