I have an entity contains a collection field
@Entity
@Table(name = "SERVICE")
public class Service {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQUENCE")
@SequenceGenerator(name = "SEQUENCE", sequenceName = "SEQUENCE")
@Column(name = "ID_SERVICE")
private Integer id;
@ElementCollection
@CollectionTable(name = "SERVICE_JOB",
joinColumns = @JoinColumn(name = "ID_SERVICE", referencedColumnName = "ID_SERVICE"))
@Column(name = "JOB")
private List<String> jobs = new ArrayList<String>();
}
I want to return services where field jobs contains my variable "job"
@Query("SELECT DISTINCT s FROM Service s WHERE ?1 in (s.jobs)")
List<Service> findByJob(String job);
It always returns an empty list although field jobs contains my variable
Any suggesstions?
Behind the scenes, Data JPA will create SQL queries based on the finder method and execute the query for us. To create finder methods in Data JPA, we need to follow a certain naming convention. To create finder methods for the entity class field name, we need to create a method starting with findBy followed by field name.
One initial approach is of course to use the built in Spring Data JPA support for searching based on declaring methods in your repository. Let’s say we want to find all employees based on their birthDate we can easily do that by declaring a query in our JPA repository interface.
To query the database that should match both name and location then we need to create a method like this – To query the database that should match any one of the columns then we need to create a method like this – Behind the scenes, Data JPA will create a SQL query like this –
Select Query In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.xml file.
try a custom query where you can use member of
like so :
@Query("SELECT s FROM Service s WHERE ?1 member of s.jobs")
List<Service> findByJobs(String job)
You can do it this way
@Query("select s from Service s WHERE :job in elements(s.jobs)")
List<Service> getAllByJobs(@Param("job") String job)
For this to work you have to change your Entity a bit, like this
public class Service {
@ElementCollection
private List<String> jobs
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With