The boy, then 14, who was not named, was in a fragile state after splitting up with his girlfriend in May and took the weapons in to his classroom.
He did not go with the intention of creating a bloodbath, ruled the regional court in Memmingen, southern Germany, but rather of impressing his former girlfriend, 13.
But one of the guns went off in his desk and he panicked, fleeing to a local sports ground where he quickly found himself surrounded by police.
During a nerve-shredding stand-off, which lasted several hours, he initially shot in the air and at the ground but then began to aim at officers. No one was hurt in the incident, which the court described as a “near miracle.”
The court on Wednesday found the boy guilty of four counts of attempted manslaughter as well as breaking gun laws. Police at the time said he was carrying two guns.
The judges said he had an “inner wildness” that came from poor upbringing. He had long considered himself a “hero who had shot at the police,” the court added.
He had apologised in a statement before he was sentenced.
The case brought back painful memories of a massacre in southwestern Germany in 2009 when 17-year-old Tim Kretschmer burst into his former school and picked off nine fellow pupils and three teachers, mostly with expert shots to the head.