A California teen pleaded guilty on Monday to second-degree murder for shooting to death a 15-year-old gay classmate at his middle school who he said made unwanted sexual advances.

The plea by Brandon McInerney, under an agreement with Ventura County prosecutors, brings to a close an emotionally charged case that previously resulted in a hung jury on a charge of murder with a hate crime enhancement.

McInerney, who was 14 at the time of the shooting in 2008, will be sentenced to 21 years in prison without time off for good behavior when he appears before a judge in December, prosecutors said.

Prosecutors said McInerney, now 17, took a gun to his middle school in Oxnard and sat in a computer lab with classmate Larry King before shooting him in the back of the head and then firing at him as he lay on the ground.

King died two days later after he was removed from life support at a local hospital.

Prosecutors initially charged McInerney as an adult and accused him of murder with hate crime and gun use enhancements, in a case that was moved to suburban Los Angeles over concerns he might not get a fair trial in Ventura County where the shooting occurred.

King, 15, was openly gay, and McInerney's attorneys argued he made sexual advances against their client.

Ventura County prosecutors said McInerney targeted King because of his sexuality and they stressed that King, far from being the aggressor, was being bullied and was 30 pounds lighter than McInerney.

After nine weeks of trial, the jury failed to agree on a verdict against McInerney, with seven voting for manslaughter and five for murder, the Ventura County District Attorney's Office said.

There was no dispute during the trial that McInerney fired the fatal shots. The judge in that trial declared a mistrial in September due to the hung jury.

In the first trial, it seemed that the jurors had a difficult time setting aside emotions and philosophies and simply judging the case on its facts, because of the age of the defendant for one thing, chief deputy district attorney Michael Frawley told Reuters.

Ventura County prosecutors refiled the case and dropped the hate crime allegation. Prosecutors and McInerney's attorneys later reached a deal that had him plead guilty to second degree murder, voluntary manslaughter and use of a gun.

But McInerney will not be sentenced on the second-degree murder charge, however, and will instead be sentenced on the manslaughter and gun use charges.

It's very unorthodox, McInerney's attorney Robyn Bramson said. Both sides wanted to resolve it for various reasons, and this was just our way of getting to something that was tolerable for both sides.

The move to not have McInerney sentenced on second-degree murder charge ensures he will serve a set term of 21 years and will not have to go before a parole board to win release, Bramson said. The agreement that we reached today accomplishes that, and for that reason we are pleased.