how to select from enum field in spring

Viewed 28

In my domain folder, I have the class Produit:

public class Produit implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Column(name = "nom", nullable = false)
    private String nom;

    @NotNull
    @Column(name = "prix", nullable = false)
    private Float prix;

    @NotNull
    @Column(name = "source", nullable = false)
    private String source;

    @NotNull
    @Column(name = "description", nullable = false)
    private String description;

    @NotNull
    @Enumerated(EnumType.STRING)
    @Column(name = "categorie", nullable = false)
    private Categorie categorie;

    @NotNull
    @Column(name = "available", nullable = false)
    private Boolean available;

    @NotNull
    @Column(name = "promo", nullable = false)
    private Boolean promo;

    @Column(name = "prix_promo")
    private Float prixPromo;
}

I'm trying to select all the entities with a specific categorie using the function in the repository:

 @Query("Select p from Produit p where p.categorie = :x")
 List<Produit> findByCategorie(@Param("x") String categorie);

The enum Category contains:

public enum Categorie {
    Bio, Alimentation, Vetement
}

In the ProduitResourse, I've configured the @GetMapping:

@GetMapping("/produits/categorie/{categorie}")
public ResponseEntity<List<Produit>> getByCategorie(@PathVariable("categorie") String categorie) {
    log.debug("REST request to get a page of Produits for a specific category");
    List<Produit> page = produitRepository.findByCategorie(categorie);
    return ResponseEntity.ok().body(page);
}  

But the server's response returns an IllegalAgrument message.

1 Answers

Just do this:

@Query("Select p from Produit p where p.categorie = :x")
List<Produit> findByCategorie(@Param("x") Categorie categorie);

Hibernate is smart enough to understand that categorie is an Enum, and parses its value to correspond the value on the database.

Related