spring-projects / spring-data-jpa

Simplifies the development of creating a JPA-based data access layer.
https://spring.io/projects/spring-data-jpa/
Apache License 2.0
2.98k stars 1.41k forks source link

Problem with Spring Data JPA with projections, specifications and SPEL #3410

Closed z8manu8z closed 5 months ago

z8manu8z commented 6 months ago

I'm having a problem using a bean in a SPEL @Value expression by combining Projections and Specifications.

Example project : spring-jpa-projections-specs.zip

In the attached project, a projection returned by a @Query works correctly, while a projection returned by JpaSpecificationExecutor.findBy(Specification spec) returns an error during http serialization.

CityProjection :

@Value("#{@projectionHelper.fullName(target.name, target.country)}") String getFullName();

In CityServiceImpl line 79 :

CityProjection = this.cityRepository.findByNameAndCountry(name, country); => works well

CityProjection = this.cityRepository.findBy(new Specification<City>() { @Override public Predicate toPredicate(Root<City> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { return null; } }, q -> q.as(CityProjection.class).firstValue());

=> fails with message :

Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: EL1057E: No bean resolver registered in the context to resolve access to bean 'projectionHelper']

How can I solve this ?

christophstrobl commented 5 months ago

@z8manu8z thank you for reporting the issue. It seems the FluentQuerySupport is not using the ProxyProjectionFactory available via RepositoryFactorySupport#getProjectionFactory() but creates its own instance. Without the BeanFactory being present the resolution of projectionHelper fails as a result of that.

christophstrobl commented 5 months ago

The fix unfortunately requires quite a few changes in the current implementation, so I'm afraid there's no easy work around for this at the moment.

z8manu8z commented 5 months ago

@christophstrobl Ok thanks for your investigations ! I can adapt my implementation, no worry about that. Can you show me how I can do ?

But I imagine the fix won't be released soon ... ?