I am using Spring Boot application. I am using following method to return List<String>
using @Query
annotation.
@Query("select c.name from Customer c")
List<String> findAllNames();
Is there a way to get the above result without @Query or @NativeQuery annotations?
CodePudding user response:
Spring Data JPA supports this quite well. You can define a POJO that represents the (reduced) object (the projection) you want of the entity, then define a method that describes the query, returns the appropriate type, and Spring Data will generate all the code necessary to execute the query and map the results.
Here's an example of a custom repository interface that uses this technique (untested pseudo-code):
public class CustomerSummary {
private String name;
// constructor and getters
}
@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long> {
List<CustomerSummary> getAllSummaries();
}
I'm not sure if you can use "simple" types such as String
in the return type, but I wouldn't be surprised if that is supported.
Also, you might have to tweak the exact method naming of `` to make sure Spring Data correctly interprets it as you want. Here is some additional reference documentation.
CodePudding user response:
You could use projection to select only name
property:
interface CustomerNameProjection {
String getName();
}
and then use it in Repository
class:
List<CustomerNameProjection> findAllProjectedBy();
edit: corrected repository method name
CodePudding user response:
Inject EntityManager and call createQuery.
entityManager.createQuery("select c.name from Customer c")
.getResultList()