Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query for join in Spring Data JPA

I want to write a join like

Select a.id,a.desc,b.desc from A a  left join B b on a.MEDIA_ID = b.ID

I have create two Entities A & B and created CrudRepository<A,Long>.

Now, in the crudRepository in need to write a method which can get the data using the above join.

Also, i created a transient variable in entity A (Names it as 'bDescription) how to achieve this in Spring Data JPA.

Note: I need join just to find out 'description'(a column in B) for a particular id(primary key in B and mapped as 'MEDIA_ID' in A) of Entity B..

Thanks in Advance

like image 428
S Atah Ahmed Khan Avatar asked Nov 18 '13 08:11

S Atah Ahmed Khan


People also ask

How do you use join fetch in JPA?

The FETCH keyword of the JOIN FETCH statement is JPA-specific. It tells the persistence provider to not only join the 2 database tables within the query but to also initialize the association on the returned entity. You can use it with a JOIN and a LEFT JOIN statement.

How do I join two entities in JPA?

You can also use the relationship attributes in JPQL queries to join related entities. The trouble starts as soon as you want to join 2 entities without a relationship attribute. JPA and Hibernate versions prior to 5.1 don't support this kind of joins, and you have to use a workaround to create an implicit cross join.


1 Answers

Here is a sample of JOIN query with SpringData

public final static String FIND_WITH_DESC_QUERY = "SELECT a,b.desc as  bDescription " + 
                                                   "FROM A a LEFT JOIN a.descriptions b " +
                                                   "WHERE a.mediaID = :id";


@Query(FIND_WITH_DESC_QUERY)
public List<Media> findWithDescription(@Param("id") Long id);

Note :

  • descriptions is the mapping of the relationship between entities A and B.
  • this assume @OneToMany Set<B> descriptions()

useful link

like image 155
ben75 Avatar answered Oct 25 '22 13:10

ben75