1

I'm using Spring Data JPA to create my own custom repository method:

@Repository
public interface LoremRepository extends JpaRepository<LoremEntity, Long> {
    List<LoremEntity> findByCocIdAndMonth_Year(Long cocId, int year);
}

My LoremEntity:

public class LoremEntity {

    // Other fields ...

    @Column(name = "MONTH")
    private ZonedDateTime month;

    @Column(name = "COC_ID")
    private Long cocId;
}

I'm getting this error:

Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.banana.pikachu.LoremRepository .findByCocIdAndMonth_Year(java.lang.Long,int)! Illegal attempt to dereference path source [null.month] of basic type at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.(PartTreeJpaQuery.java:96) at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:103) at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:209) at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:78) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lookupQuery(RepositoryFactorySupport.java:574) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(RepositoryFactorySupport.java:567) at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195) at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)

How to fix this issue?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Tung Vo
  • 2,227
  • 5
  • 27
  • 45
  • 1
    That won't work as you cannot query for a property of `ZonedDateTime`, that would only work if `ZonedDateTime` would be an entity. So you would need to query in a range. Start of year and end of year instead of only the year. – M. Deinum Jul 29 '21 at 10:06

1 Answers1

0

You can use year function (and other functions) in your JPQL (HQL) query, for example like this:

@Query("select l from LoremEntity l where l.cocId = ?1 and year(l.month) = ?2")
List<LoremEntity> findByCocIdAndMonth_Year(Long cocId, int year);

If you want to do it with CriteriaQuery see here: https://stackoverflow.com/a/52530845/2039546

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29