JPA Query return List of Entites

531 Views Asked by At

I have a class Event

@Entity 
public class Event {

@Id // PrimaryKey
@GeneratedValue(strategy = GenerationType.AUTO) 
private int event_id;
private String bezeichnung;
private Date startzeitpunkt;
private Date endzeitpunkt;
private boolean abgeschlossen;

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "event_unternehmen", joinColumns = @JoinColumn(name = "event_id"))
@Column(name = "unternehmen_id")
private Set<Integer> teilnehmendeUnternehmen; 

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "event_studierender", joinColumns = @JoinColumn(name = "event_id"))
@Column(name = "student_id")
private Set<Integer> teilnehmendeStudierende; 

I want to get a List of all event_ids, where a specific student_id is in the objectattribute teilnehmende_Studierende (Set)

I tried something like this:

@Query("SELECT e FROM Event e WHERE e.teilnehmendeStudierende=:userId") 
List<Event> findByUserId(@Param("userId") int userId);  

But it gives me following error:

Caused by: java.lang.IllegalArgumentException: Parameter value [28] did not match expected type [java.util.Set (n/a)] at deployment.speeddating-web-7.0-SNAPSHOT.war//org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:54)

1

There are 1 best solutions below

2
On

You should use in operator as in your query you cannot assign a set to a single value. Please try :

Repository :

public interface EventRepository extends JpaRepository<Event, Long> {
    List<Event> findByTeilnehmendeStudierendeIn(int userId);
}

Test class :

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Autowired
    private EventRepository eventRepository;

    @Test
    public void test() {
        Event e = new Event();
        e.setTeilnehmendeStudierende(new HashSet<Integer>(Arrays.asList(1, 2)));
        eventRepository.save(e);
        System.out.println("Size " + eventRepository.findByTeilnehmendeStudierendeIn(1).size());
    }
}