Lingesh
Lingesh

Reputation: 11

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

Upvotes: 1

Views: 1899

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 9492

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.

Upvotes: 2

Related Questions