Home > Software design >  Can we get only specific column from a table using Spring JPA
Can we get only specific column from a table using Spring JPA

Time:07-11

I have to fetch data from a table having 100 columns, how can I implement this without creating pojo of all the fields using Spring JPA?

CodePudding user response:

You can use Interface-based Projections, create interface with only the attributes required and write abstract method in repository to return interface, for example

A projection interface to retrieve a firstname and lastname attributes

interface NamesOnly {

 String getFirstname();
 String getLastname();
}

A repository using an interface based projection with a query method

interface PersonRepository extends Repository<Person, UUID> {

  Collection<NamesOnly> findByLastname(String lastname);
}

CodePudding user response:

Such queries sometimes called scalar queries. Basically you will need to write a native query and help Hibernate what fields you are getting. Here are few links that explain the issue:

  1. Hibernate Tip: Best Way To Work with Scalar Projections,
  2. Native Queries – How to call native SQL queries with JPA & Hibernate,
  3. Hibernate’s addScalar() Method
  • Related