Search code examples
javaspringannotationsprojection

Using projection without the annotation @Projection


Situation

I inherited some code from a developer that seems to have used undocumented features of spring.

Specifically, it is related to using @projection functionality without actually annotating the interfaceas such.

A specific example is the following:

public interface DirType extends KeyValInterface  {
    @Value("#{target.id}") String getId();
    @Value("#{target.code}") String getText();
}

This should not work according to the official documentation, but it does.

public interface DirTypeRepository extends JpaRepository<ABDirType, Long> {
    List<DirType> findAllSummarizedBy(); 
}

So the method findAllSummarizedBy() of the respository is actually sending a list of DirType.

And it is using the @Valueannotations to do the mapping, but without a @Projection annotation.

The Entity class is the following:

@Data @Entity @Table(name="dir_type") @AllArgsConstructor @NoArgsConstructor
    public static class ABDirType {

        private @Id @GeneratedValue Long id;
        private String code;
    }

Question

Does anyone have any more information about this undocumented feature related to Projections and not annotating the interface as a @Projection ?

Is this possible in all versions or is it a hidden hack that is risky to use?


Solution

  • In Spring Data JPA (which you seem to be using here), you can simply use an interface with appropriate getters as projection targets.

    See the documentation about this (esp. "Example 62. Simple Projection").

    There does not seem to be a @Projection annotation anywhere in the documentation.