Projection in Spring Boot JPA allows you to fetch specific columns from a table instead of the entire entity. This improves performance by reducing data transfer.
Using Interface-Based Projection
The simplest way to fetch specific columns is by defining an interface projection
Example: Fetching Only idand namefrom User
User.java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private int age;
// Getters and Setters
}
Define a Projection Interface
public interface UserProjection {
Long getId();
String getName();
}
Modify Repository to Use Projection
public interface UserRepository extends JpaRepository {
// Fetch only id and name
List findByAgeGreaterThan(int age);
}
Fetch Data in Service Layer
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List getUsersByAge(int age) {
return userRepository.findByAgeGreaterThan(age);
}
}
✅ Advantage: More flexible, can handle complex queries.
Using DTO (Data Transfer Object) Projection
Example: Fetching id, name, and ageinto a DTO
UserDTO.java
public class UserDTO {
private Long id;
private String name;
private int age;
public UserDTO(Long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// Getters
public Long getId() { return id; }
public String getName() { return name; }
public int getAge() { return age; }
}
Modify Repository to Use DTO
public interface UserRepository extends JpaRepository {
@Query("SELECT new com.example.dto.UserDTO(u.id, u.name, u.age) FROM User u WHERE u.age > :age")
List findUsersByAge(@Param("age") int age);
}
Service Method
public List getUsersByAge(int age) {
return userRepository.findUsersByAge(age);
}
We use cookies and similar technologies to enhance your browsing experience, serve personalized content and advertisements, and analyze our traffic.
By clicking "Accept All", you consent to our use of cookies and the processing of your personal data for these purposes.
You can manage your preferences or learn more in our
Privacy Policy and
Cookie Policy.