I am using Spring JPA and in order to ad a List of String to my Entity I am using @ElementCollection as below.
@ElementCollection
private Map<Integer, String> categories;
When I use this it generates a table called subscription_categories
this contains the following columns subscription(varchar), catergories(varchar) and caterogies_key (int)
If I use my SQL tool on my desktop I can query this table fine with the following
select `subscription_categories`.`subscription` from `subscription_categories` where `subscription_categories`.`categories`='TESTING';
However, when I attempt to use this in Spring Data it fails with a "... not mapped" error
Here are a few attempts below:
@Query("select s.subscription from subscription_categories s where s.categories = ?1")
List<Subscription> findUsernameByCategory(String category);
@Query("select s.subscription from categories s where s.categories = ?1")
List<Subscription> findUsernameByCategory(String category);
Both return the same error.
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: categories is not mapped
My question is this:
How can I query the table created by the @ElementCollection?
You can't directly query from @ElementCollection
. You should query base entity (I assume its name is Subscroption
).
@Query("select s from Subscroption s where s.categories = ?1")
List<Subscription> findUsernameByCategory(String category);
If you want query by key, then use
@Query("select s from Subscroption s where index(s.categories) = ?1")
List<Subscription> findUsernameByCategoryKey(Integer key);