Strategy Customizado - Cancelando execução[Resolvido]

7 respostas
F

Dae pessoal...

Estou desenvolvendo uma aplicação onde o usuário é que irá definir o ID no cadastro de cliente, com isso definir
o @GenericGenerator(name= "geradorMatricula", strategy="helper.GeradorMatricula").

Estou fazendo as validações e esta tudo certo, mas não consigo cancelar a persistência do objeto. Alguém ja teve esta experiência?

segue código:

public Serializable generate(SessionImplementor si, Object o) throws HibernateException {

        CadastroAlunoEntity obj = (CadastroAlunoEntity) o;
        int matricula = obj.getPkAluno();

        try {
            //Verifica se ja existe o registro
            CadastroAlunoEntity c = (CadastroAlunoEntity) HibernateHelper.getById(CadastroAlunoEntity.class, matricula);
            if (c != null) {
               Mensageiro.errorMsg("A Matrícula informada já está em uso. Aluno " + c.getNome());
               
             return null;//ele da erro se retorno nulo porque a transação é continuada, o que preciso é cancelar toda transação e retorna pra tela a mensagem.
            }

        }catch (Exception e) {
            new DAOException(e.getMessage());
        }

        return new Integer(matricula);

    }

7 Respostas

C

Fernando,

Brow… Quando postar código procure colocar entre as tags [ code] e [/ code].

public Serializable generate(SessionImplementor si, Object o) throws HibernateException { 
    CadastroAlunoEntity obj = (CadastroAlunoEntity) o; 
    int matricula = obj.getPkAluno(); 
    try { 
        //Verifica se ja existe o registro 
        CadastroAlunoEntity c = (CadastroAlunoEntity) HibernateHelper.getById(CadastroAlunoEntity.class, matricula); 
        if (c != null) { 
            Mensageiro.errorMsg("A Matrícula informada já está em uso. Aluno " + c.getNome()); 
            return null; //ele da erro se retorno nulo porque a transação é continuada, o que preciso é cancelar toda transação e retorna pra tela a mensagem. 
        } 
    }catch (Exception e) { 
        new DAOException(e.getMessage()); 
    } 
    return new Integer(matricula); 
}

Inicialmente, se vc deseja interromper a execução basta disparar uma exceção nesse seu if(c != null), e detalhe, por boas práticas de programação nunca utilize mais de um return em seu método.

E no seu método original vc estava criando um objeto DAOException, mas não estava disparando a exceção com um throw.

public Serializable generate(SessionImplementor si, Object o) throws HibernateException, DAOException { 
    CadastroAlunoEntity obj = (CadastroAlunoEntity) o; 
    int matricula = obj.getPkAluno(); 
    try { 
        //Verifica se ja existe o registro 
        CadastroAlunoEntity c = (CadastroAlunoEntity) HibernateHelper.getById(CadastroAlunoEntity.class, matricula); 
        if (c != null) { 
            throw new DAOException("A Matrícula informada já está em uso. Aluno " + c.getNome()"); 
        }
    }catch (Exception e) { 
        throw new DAOException(e.getMessage()); 
    } 
    return new Integer(matricula); 
}

A mensagem de erro vc deixa para tratar na camada de apresentação. Acredito que lá vc poderá utilizar esta chamada de método estático.

Mensageiro.errorMsg(ex.getMessage())

@braços

F

Como só consigo testar quando estiver em casa, na night, te dou um retorno se deu certo.

Valeu pelo toque.

F

Hi ccllss,
Ja deu uma luz o seu post, mas não conseguir fazer o que queria.

Seguinte,

Este é o meu estrategy:

public class GeradorMatricula implements IdentifierGenerator {

    public Serializable generate(SessionImplementor si, Object o) throws HibernateException {
        CadastroAlunoEntity obj = (CadastroAlunoEntity) o;
        int matricula = obj.getPkAluno();


        try {
            CadastroAlunoEntity c = (CadastroAlunoEntity) HibernateHelper.getById(CadastroAlunoEntity.class, matricula);
            if (c != null) {
               throw new HibernateException(c.getNome());
            }
        } catch (HibernateException e) {
            new HibernateException(e.getMessage());
            //new DAOException(e.getMessage());
        }  catch (Exception e) {
            new DAOException(e.getMessage());
        }

        return new Integer(matricula);



    }
}

O meu action do jsf chama a funcão save no MB.

public String save() {
         try {
              HibernateHelper.save(alunoCorrente);
            Mensageiro.infoMsg("cadastroOK");
            setAlunoCorrente(new CadastroAlunoEntity());


        } catch (DAOException e) {
            new DAOException(e.getMessage());
            //return "erro";
        } catch (HibernateException e) {
            new DAOException(e.getMessage());
            return "erro";
        } catch (Exception e) {
            new DAOException(e.getMessage());
            return "erro";
        }

        return null;
    }

O MB chama o save do HibernateHelper

public static void save(Object obj)throws DAOException  {
        Session session = null;
        Transaction tx = null;
        try {
            session = getSessionFactory().openSession();
            tx = session.beginTransaction();//Mesmo com uma   hibernateException(lançada pela verificação do strategy) ele continua o processo e tentar salvar o objeto, depois de tentar salvar é que da um erro porque já existe uma key.  
            session.save(obj);
            tx.commit();
        }catch (HibernateException hbe) {
            if (tx != null) {
                tx.rollback();
            }        
           throw new DAOException(hbe.getMessage());        

        }catch (Exception e){
           throw new DAOException(e.getMessage());
        }

        finally {
            if (session != null) {
                session.close();
            }
        }
    }

Ja tentei de várias formas, mas ainda não a correta. Um unico jeito que consegui até o momento, mas é na Gambi, foi colocar a verificação antes de chamar o metodo hibernateHelper.save no meu MB. Da certo, mas não é ali que esta verificação deve ficar.
Continuo na luta...

C

FernandoMelo,

Como te falei anteriormente… Neste trecho de código do seu GeradorMatricula vc cria novas exceções mas não as dispara.

} catch (HibernateException e) {   
            new HibernateException(e.getMessage());   
            //new DAOException(e.getMessage());   
        }  catch (Exception e) {   
            new DAOException(e.getMessage());   
        }

O correto é vc fazer assim:

} catch (HibernateException e) {   
            throw new HibernateException(e.getMessage());   
        }  catch (Exception e) {   
            throw new DAOException(e.getMessage());   
        }

No save do seu ManageBean vc comete o mesmo erro. O correto é assim:

} catch (DAOException e) {   
        throw new DAOException(e.getMessage());   
        //return "erro";   
    } catch (HibernateException e) {   
        throw new DAOException(e.getMessage());   
        return "erro";   
    } catch (Exception e) {   
        throw new DAOException(e.getMessage());   
        return "erro";   
    }

@braços

F

Erros corrigidos e problema resolvido.

Valeu pelo toque…

até!

C

FernandoMelo,

Faz a gentileza de editar seu primeito post e colocar [RESOLVIDO]

@braços

F

Valeu

Criado 21 de abril de 2010
Ultima resposta 24 de abr. de 2010
Respostas 7
Participantes 2