I have the following class called "UserInterest". It follows the following definition:
@Table(name = "user_interests")
public class UserInterest {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_interest_pk_generator")
@SequenceGenerator(name = "user_interest_pk_generator", sequenceName = "user_interest_id_seq",
allocationSize = 1)
@Column(name = "user_interest_id")
private int userInterestId;
@Column(name = "user_id", nullable = false)
private int userId;
@ElementCollection
@CollectionTable(name = "user_interest_ids")
@Column(name = "interest_id")
private List<Integer> interests;
}
JPA automatically creates the embedded table user_interest_ids
, the collection table.
This class works fine, user interest is being saved correctly.
Now I need to filter the users based on particular interest list.
Let's say I have the following user_interest
list:
And the CollectionTable looks like this:
I want to find the users who has interest id 3
. In PostgreSQL's pgAdmin panel, the query to filter interest_id =
3 return this table:
I tried to implement this filter query in Spring Data JPA, in native query by a inner join query:
@Query(value = "select user_id from user_interests inner join user_interest_ids on interest_id = ?1", nativeQuery = true)
Set<Integer> findUsersByInterest(int interestID);
This inner join query returns all the user, not only the users who has interest id 3.
I tried to find some helpful resources here in Stack overflow and other sources in internet, unfortunately I could not manage to find helpful resources for my problem.
Could you please give me some advices how to implement this query as native query inside Spring Data JPA or some links of other sources where I could find the helpful resource for my question.
I really appreciate your help.