The four-time Hamburg champion is playing his first tournament since losing in the second round of Wimbledon.
Federer won only three of 13 break points and needed six match points to close out the match. He did it with his seventh ace, shortly after producing a spectacular overhead smash winner with a flick of the wrist while stepping back in the final game.
The 17-time Grand Slam champion needed five set points to end the first set, finally earning it when Hajek netted a forehand.
The German led 5-2 in the second set but dropped serve. He then wasted two match points on Berlocq's serve before using his fourth to close out the second-round encounter, hitting a cross-court forehand winner. Berlocq won his first title last week in Bastad, Sweden.
Fourth-seeded Wimbledon semifinalist Jerzy Janowicz of Poland was forced to retire with a right arm injury, allowing 14th-seeded Fernando Verdasco to advance. The Spaniard, who was leading 7-5, 4-0, will play Argentine qualifier Federico Delbonis, who beat Dmitry Tursunov of Russia 6-4, 6-3.