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
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.
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.
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.@OneToMany Set<B> descriptions()
useful link
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