Selecting specific columns (or a subset of columns) in Spring Data JPA can be achieved using multiple ways, but one of the most common approaches is using JPQL in combination with DTO projections. In this guide, I'll demonstrate how to select specific columns using this approach.
1. Setting up the project
Make sure you have the required dependencies in your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2. Define the Entity
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private Date dateOfBirth;
// getters, setters, etc.
}
3. Create a DTO Projection
public class PersonNameDto {
private final String firstName;
private final String lastName;
public PersonNameDto(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// getters
}
Note the final keyword for fields and the constructor to initialize these fields. 4. Create the Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
@Query("SELECT new com.yourpackage.PersonNameDto(p.firstName, p.lastName) FROM Person p")
List<PersonNameDto> findAllNames();
}
The above query selects only the firstName and lastName from the Person entity and maps them to the PersonNameDto. 5. Use the Repository in a Service
@Service
public class PersonService {
@Autowired
private PersonRepository personRepository;
public List<PersonNameDto> getPersonNames() {
return personRepository.findAllNames();
}
}
6. Test the Service
@SpringBootTest
public class PersonServiceTest {
@Autowired
private PersonService personService;
@Test
public void testFetchNames() {
List<PersonNameDto> names = personService.getPersonNames();
for (PersonNameDto name : names) {
assertNotNull(name.getFirstName());
assertNotNull(name.getLastName());
}
}
}
Comments
Post a Comment
Leave Comment