简体   繁体   中英

Spring many to many select

public class User {
    @ManyToMany(mappedBy = "speakers")
    private List<Event> speakerEvents;
}

public class Event {
    @ManyToMany
    @JoinTable(name = "user_speaker_event",
            joinColumns = {@JoinColumn(name = "event_id")},
            inverseJoinColumns = {@JoinColumn(name = "calendar_user_id")})
    private List<User> speakers;
}

I want to select all speakers => I need all Users with spekaerEvents is not null.

I'm using Spring Data, and tried to user repository with method, but it's not working.

It returns all speakers, but speakers duplicated (so there will be 5 times User1, 5 times User2 etc)

public interface UserRepository extends JpaRepository<User, Long> {    
    List<User> getBySpeakerEventsIsNotNull();
}

I know i can use @Query annotation to select needed users, but I can't figure it out (query itself).

I have something like this, but it's working same way. I feel like I need add DISTINCT somewhere, but do not know how.

SELECT * 
FROM public.calendar_users
INNER JOIN user_speaker_event ON calendar_users.id = user_speaker_event.calendar_user_id

Okay I figured it out.

@Query("select u from User u where u.speakerEvents.size <> 0")

My main problem was ofcouse bad understanding of jpql and sql too.
But idea "helped" me a bit here too. There wasn't installed facet for JPA, and it just don't wanted to use speakerEvents.size, so I thoght it's not supported. And further more, it was trying to take database User, not my application user => there was more errors. When I saw userName "postgres" in debug, I finally understood what happening there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM