3

I created a method which through spring data automatically create the query. The problem is about the return param, because dismatch from the name definition. In fact by specifying only one parameter, it return 4 parameters.

The springData method is that:

Optional<Comunicazioni> getCommIDByExtIDAndCommSAndCommT(
    BigDecimal extID, String commS, String commT);

and I access to the type like so:

getCommIDByExtIDAndCommSAndCommT(extId, commS, commT).get().getCommID()

how can I retrieve only the column I need?

Thank you

JKRT
  • 1,179
  • 12
  • 25
osharko
  • 204
  • 3
  • 19
  • if you can use natice query method you can return only you need fileds.see this [answer](https://stackoverflow.com/questions/22007341/spring-jpa-selecting-specific-columns) – TongChen Jan 21 '19 at 14:59
  • can i mix query by method's name and native query into a single call? – osharko Jan 21 '19 at 15:07
  • you can learn more from [Query Lookup Strategies](https://docs.spring.io/spring-data/jpa/docs/2.1.4.RELEASE/reference/html/#repositories.definition) – TongChen Jan 21 '19 at 15:12
  • i'm sorry, i didn't find a line that tell to me that i query by method's name and by query annotation at same time. did you know if it's possibile or i must query by @query? – osharko Jan 21 '19 at 15:37
  • Yes, a method `@Query("select u.id, LENGTH(u.firstname) as fn_len from User u where u.lastname like ?1%") List findByAsArrayAndSort(String lastname, Sort sort);` – TongChen Jan 21 '19 at 16:05
  • Instead of using @Query you should also take a look at [projections](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections) – C. Weber Jan 21 '19 at 16:17
  • TongChen i'm not able using in this way, i used a simply @Query on methods because i don't succed in the other way – osharko Jan 22 '19 at 08:03
  • hi @C.Weber this solution was the same as my primary implementation, but now i don't want the entity as return type, but the flat value – osharko Jan 22 '19 at 08:05

1 Answers1

4

Unfortunately, this is not possible with the current implementation of Spring Data JPA (i.e. Using method name only).

Instead, the current solution is to use @Query to define the return values. You can find an example of that here.

However, if your Entity object is not too large, you would be able to achieve the result in the example you posted by simply retrieving the entire entity:

Optional<Comunicazioni> findByExtIDAndCommSAndCommT(BigDecimal extID, String commS, String commT);

and then calling it as

repo.findByExtIDAndCommSAndCommT(extId, commS, commT).get().getCommID();

It would be nice to see this functionality in the future, but for now, it is not so difficult to work around.

ShadowOfLies
  • 130
  • 6