Energetics and formation mechanism of borders between hexagonal boron nitride and graphene