Skip to content
Advertisement

JPA Specification for Enum

My JPA Entity as an Enum field

@Table(name="zsrb_ordini_prod")
@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class OrdineProd implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long idOrdineProd;

    ...

    @Enumerated(EnumType.STRING)
    public StOrdine stato = StOrdine.CREATO;

    ...
}

Where

public enum StOrdine {
    CREATO,
    SCHEDULATO,
    CONFERMATO,
    SCARTATO
}

If I add a where condition with a specification

Specification<OrdineProd> = (root, query, qb)->
                qb.equal(root.get("stato"), StOrdine.SCHEDULATO);


java.lang.IllegalArgumentException: Parameter value [SCHEDULATO] did not match expected type [imp.srb.progettazione.ordProd.StOrdine (n/a)]
    at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:54) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
    at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:27) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
...
    

what is the correct way to include Enums into Specification queries?

Advertisement

Answer

Try doing this:

Specification<OrdineProd> = (root, query, qb) ->
            qb.equal(root.get("stato"), StOrdine.SCHEDULATO.name);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement