Rafael Nadal is attempting to win Barcelona Open for a record 12th time.
Nadal in the next round, with a place in the quarter-finals at stake. Nadal has won all of his last four meetings with Ferrer.
“It was a tough start, I didn’t have the feeling this afternoon. I just found a way to keep going and win,” admitted Nadal.
“He competed well and I was probably not competing that well. My attitude was solid but I had to work hard to stay in the tournament.”
Nadal, who has 25-6 winning record against Ferrer, added: “Playing David is never easy, especially since he’s such a friend. I’m expecting a tough match.”
Mayer, ranked 63rd in the world, had never beaten a top-five opponent in 15 attempts but was more than a match for a nervous-looking Nadal in the opening set.
Nadal will be gunning for title number 12 at Roland Garros too and this recovery will have given him much relief, after the 17-time major champion was a shock semi-final loser to Fabio Fognini at the Monte Carlo Masters last week.
A poor game allowed Nadal to break to love at 4-3 in the first set but Mayer hit back for 5-5 and held on for a tie-break.
Nadal looked in control after recovering from 3-1 and 4-2 down to set up two set points but he squandered both before Mayer took his chance at the first time of asking, a booming forehand enough to clinch the set.
An early break at the start of the second sent Nadal on his way and he served out at 5-4 to take the match to a decider.
Mayer seemed to have lost belief as he dumped a simple backhand volley into the net, allowing his opponent to seize a crucial break at 2-2.
From there, the momentum was set as Nadal whipped a forehand down the line for 5-2 and then served out to complete a hard-fought win.