package jm28;

import java.util.*;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class ListaCategoriasMunicipio2 {
    
    public static void main(String[] args) {

        SessionFactory sessionFactory =
            new Configuration().configure().buildSessionFactory();
            
        Session session = sessionFactory.openSession();
            
        Transaction tx = session.beginTransaction();
        
        Query query = session.createQuery(
            "select cli from Cliente as cli " +
            "join fetch cli.categoria cat " +
            "where cli.endereco.municipio = 'Gothan City' " +
            "order by cat.nome, cli.nome");
        Iterator<Cliente> it = query.list().iterator();        
        Categoria anterior = null;
        while (it.hasNext()) {
            Cliente cli = it.next();
            Categoria cat = cli.getCategoria();
            if (cat != anterior) {
                System.out.println("[" + cat.getId() + "] "
                    + cat.getNome());
            }
            anterior = cat;
            System.out.println("\t[" + cli.getId() + "] "
                + cli.getNome());
        }
        
        tx.commit();
        
        session.close();
    }
    
}
