The military can put you in jail for not fulfilling your end of the bargain. On top of that, there are no competing militaries - you can't decide in year 2 of you contract to go work for a different military, so there is a low risk on the part of the military for paying for the initial training.