Fetch selected columns from two or more table using Spring Jpa

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Fetch selected columns from two or more table using Spring Jpa


@Entity
public class A
//some properties



@Entity
public class B
//Some properties



I want to fetch selected columns from two tables using JPA, I know how to fetch single Entity table data through Repository and Controllers.



Repository:


public interface extends JPARepository<A, Long>
List<A> findAll();



Controller:


public class class_name
@AutoWired
private JPARepository repo;
@RequestMapping("/data")
public List<A> getData()
return repo.findAll();




Above code is to fetch single table data. Now, I want to fetch selected columns from both the tables.


Note: A, B Entities have mappings




1 Answer
1



What you can do is to use @Query annotation on one of your methods in the repository and performs something like this:


public Name
String firstName;
String telephone;

public Name(String firstName,String telephon)
//initialize fields



@Query(select new dummy.Name(u.name,c.telephone) from User u join fetch u.contact c where u.externalId= ?1 )
public Name getName(String externalId)



You can return easily List instead of using constructor query , but i find it cleaner this way.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard