Spring JPA - "java.lang.IllegalArgumentException: Projection type must be an interface!" (using native query)

I'm trying to retrieve a timestamp date from an oracle database but the code is throwing:

java.lang.IllegalArgumentException: Projection type must be an interface!

I'm trying to use native query because the original query is way to complex to use Spring JPA methods or JPQL.

My code is similar to this one below (Sorry, can't paste the original one due to company policy).

Entity:

@Getter
@Setter
@Entity(name = "USER")
public class User {

    @Column(name = "USER_ID")
    private Long userId;

    @Column(name = "USER_NAME")
    private String userName;

    @Column(name = "CREATED_DATE")
    private ZonedDateTime createdDate;
}

Projection:

public interface UserProjection {

    String getUserName();

    ZonedDateTime getCreatedDate();
}

Repository:

@Repository
public interface UserRepository extends CrudRepository<User, Long> {

    @Query(
            value = "   select userName as userName," +
                    "          createdDate as createdDate" +
                    "   from user as u " +
                    "   where u.userName = :name",
            nativeQuery = true
    )
    Optional<UserProjection> findUserByName(@Param("name") String name);
}

I'm using Spring Boot 2.1.3 and Hibernate 5.3.7.

1 answer

  • answered 2019-03-19 18:09 Alien

    You have declared userId field as Long in the entity but in UserProjection getUserId method return type is String. which is mismatching so Change

    String getUserId();

    to

    Long getUserId();