Jason
Jason

Reputation: 7656

Why is my projection interface not picked up by Spring Data REST?

I am trying to use up projections with Spring Data REST (version 2.3.0.RELEASE). I read the reference documentation, and gathered that these are the parts I need:

A JPA Entity

@Entity
public class Project implements Serializable {

    @Basic(optional = false)
    @Column(name = "PROJECT_NAME")
    private String projectName;

    // ... lots and lots of other stuff
}

A repository that works with that entity

@Repository
public interface ProjectRepository extends JpaRepository<Project, Long> { }

And a projection to retrieve just the name for that entity

@Projection(name="names", types={Project.class})
public interface ProjectProjectionNamesOnly  {

  String getProjectName();
}

I would like to be able to optionally retrieve just a list of names of projects, and projections seemed perfectly suited to this. So with this setup, I hit my endpoint at http://localhost:9000/projects/1?projection=names. I get back ALL of the attributes and collections links, but I expected to get back just the name and self link.

I also viewed the sample project on projections, but the example is for excerpts, which seems different from projections as it is a different section of the reference. I tried it and it didn't work anyway though.

So the question is this: How do you use spring data rest projections to retrieve just a single attribute of an entity (and its self link)?

Upvotes: 2

Views: 6305

Answers (1)

Oliver Drotbohm
Oliver Drotbohm

Reputation: 83131

Looks like your projection definition is not even discovered and thus it doesn't get applied if you select it for the HTTP request.

For projection interfaces to be auto-discovered they need to be placed inside the very same or a sub-package of the package of the domain type they're bound to.

If you can't put the type into that location, you can manually register a projection definition on RepositoryRestConfiguration by calling ….projectionConfiguration().addProjection(…).

The reference documentation does not really mention this at the moment but there's already a ticket to get this fixed in future versions.

Upvotes: 14

Related Questions