Home JPA or JPQL how to return single row from a many to many relationship
Reply: 1

JPA or JPQL how to return single row from a many to many relationship

frododot
1#
frododot Published in 2018-01-13 02:17:34Z

Learning JPA and JPQL. I have 3 database tables (as example): TVShow and Genre, and a Join table show_genre (having only show_id and genre_id) for the many-to-many relationship between tvShow and genre.

I have 2 annotated Java entities : Genre.java:

  @JsonManagedReference(value="showToGenre")
  @ManyToMany(mappedBy="genres", fetch=FetchType.EAGER)
  private Set<TVShow> tvShows;

and TVShow.java

@JsonBackReference(value="showToGenre")
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name="show_genre",     
        joinColumns=@JoinColumn(name="show_id"),   
        inverseJoinColumns=@JoinColumn(name="genre_id")  
)
private Set<Genre> genres;

Is there a JPA or JPQL way to find a specific row in this Many to Many, like given a genre id, and a tvShow id, can I find the specific genre object for the given tvShow id?

Israel Merljak
2#
Israel Merljak Reply to 2018-01-13 02:27:09Z
em.createQuery("Select s from show join show.genres g where g.id = :genreId")
.setParameter("genreId", id)
.setMaxResults(1)
.setFirstResult(0)
.getResultList().get(0)
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.294941 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO