Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data: Query list of string annotated with @ElementCollection

If I have an entity with this structure:

@Entity
public class RecipeRaw {
    @Id
    @GeneratedValue
    Long id;

    @ElementCollection
    List<String> listOfIngredients=new LinkedList<String>();

and I want to get a list containing all ingredients that contains the word X in it. How to do that?

for example if the word is beef, I want to get a list of ingredients like 'ground beef' , 'dried beef with salt' and so on.

I tried

@Query("select ings_temp from 
        (select rr.listOfIngredients ings_temp from RecipeRaw rr) ings 
        where ings LIKE '?1'")

But this throws an error. Is there any simple way to do this query?

like image 216
Mohamed Taher Alrefaie Avatar asked Sep 07 '25 15:09

Mohamed Taher Alrefaie


1 Answers

I solved it by this

@Query("SELECT DISTINCT t FROM RecipeRaw rr JOIN rr.listOfIngredients t "
            + "WHERE t LIKE CONCAT('%', :ing_name, '%')")
    List<String> findIngredientsByLikeName(@Param("ing_name") String name);
like image 80
Mohamed Taher Alrefaie Avatar answered Sep 10 '25 06:09

Mohamed Taher Alrefaie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!