java / intermediate
Snippet
DTO Projection using Class Constructors in JPQL
Instead of fetching the entire JPA entity, you can use the 'new' keyword in JPQL to project specific fields directly into a Data Transfer Object (DTO). This reduces memory usage and improves query performance by retrieving only required data.
snippet.java
1
2
3
4
public interface UserRepository extends JpaRepository<User, Long> {@Query("SELECT new com.example.UserDTO(u.username, u.email) FROM User u WHERE u.id = :id")UserDTO findUserDTOById(Long id);}
spring
Breakdown
1
SELECT new com.example.UserDTO(...)
Instructs JPA to instantiate the specified DTO class using its constructor.
2
u.username, u.email
The specific fields from the entity that match the DTO constructor arguments.