Enum as Parameter NamedQuery Hibernate

2

Is there any way to pass as a parameter in a NamedQuery the value of Enum .

public enum TipoConta{
   CREDITO("Cartao de Credito"), DEBITO("Cartao de Debito");
   private final String descricao;

   TipoConta(String descricao) {
    this.descricao = descricao;
   }

   @Query("SELECT g FROM Gasto g WHERE g.transacao.tipo.nome = TipoConta.DEBITO.descricao")
   List<Gasto> findAllGastos();
}

This is an example of what I'd like to do, in my code I need to pass as condition, and I'll give a description. But I would not like to leave as hard code in Query , and pass a constant of a Enum , so I only change the Enum and change in all Query .

    
asked by anonymous 15.01.2015 / 16:33

2 answers

4

You can pass parameters to a named query in the same way that you pass any JPA query.

Using standard JPA, prepare the query to receive the parameter:

@NamedQuery(
    name="findAllGastos",
    queryString="SELECT g FROM Gasto g WHERE g.transacao.tipo.nome = :tipoConta")

And to consume it:

Query query = em.createNamedQuery("findAllGastos");
query.setParameter("tipoConta", TipoConta.DEBITO.descricao);

And using Spring (your case):

@Query("SELECT g FROM Gasto g WHERE g.transacao.tipo.nome = :tipoConta")
List<Gasto> findAllGastos(@Param("tipoConta") String tipoConta);

Perhaps these parameter names are not legal because where we are saying "Account type" we are actually wanting to receive the "account type description" ; and we're comparing this "description" with a "name" ( Spend.transaction.type.name ). Consider refactoring this.

One last tip - do not publish complex business methods in an enum. Try to use the enum for what it proposes: group constants in a cohesive and strongly typed way.

    
15.01.2015 / 16:57
2

I do not know if I understand you very well, but see if that suits you.

Switch your enum to constants, because annotation does not allow you to receive instance parameters. As quoted on and nessa OS issue.

public enum TipoConta{

    // Troque seu enum para constantes, pois annotation não permite receber parâmetros de instância
    public final static String CREDITO = "Cartao de Credito";
    public final static String DEBITO = "Cartao de Debito";
}

And in the query:

// concatene a query a valor do enum (Você também pode parametrizar que é mais adequedo, eficiente e seguro)
@Query("SELECT g FROM Gasto g WHERE g.transacao.tipo.nome = " + TipoConta.DEBITO)
List<Gasto> findAllGastos();
    
15.01.2015 / 16:40