Antoniossss
Antoniossss

Reputation: 32535

Is it possible to specify property name on projection class in Spring data?

So I have following projection class

@Data
@AllArgsConstructor
public class CommentDTO3 {

    private Long id;

    private String comment;

    private Long userId;

    private Long placeId;

    private String userUserProfileFirstName;
}

This works just fine, however I would like to have userUserProfileFirstName property named as comentator_name. Is it possible to do something like this:

@Value("user.userProfile.firstName")
private String userUserProfileFirstName;

I have tested that particular example, but @Value annotation seems to be neglected. I am not interested in using @Query annotation to provide custom constructor.

Edit:

This is what works for me:

@JsonProperty("userName")
private String userUserProfileFirstName;

This one works not

@JsonProperty("userName")
@Value("#{target.user.userProfile.firstName}")
private String userName;

and it fails on startup with :

org.springframework.data.mapping.PropertyReferenceException: No property name found for type User! Traversed path: Comment.user.

https://gist.github.com/Antoniossss/7ab00c180013f707ef9a8cdc2d53e807

Upvotes: 3

Views: 2807

Answers (2)

Marcel
Marcel

Reputation: 780

Interface-based, both @Value and @JsonProperty worked out of the box in my case, e.g. this one

@Projection(types = { Project.class }, name = "website")
public interface ProjectWebAPIProjection {
  Long getId();

  @JsonProperty("geo-x")
  @Value("#{target.objekt?.xKoordinate}")
  Double getGeoX();

// ...
}

Upvotes: 1

Cepr0
Cepr0

Reputation: 30399

I don't have an experience in using class-based projections with @Value, but with 'interface' projections we can use @Value to provide some computation:

public interface CommentProjection {

    Long getId();

    String getComment();

    @Value("#{target.user.id}")    
    Long getUserId();

    @Value("#{target.place.id}")              
    Long getPlaceId();

    @Value("#{target.user.userProfile.firstName}")
    String getComentatorName();
}

UPDATE

I've checked a class-based projections - they doesn't work with @Value. The trying to use a DTO property name that differs from the Entity property name leads to throwing an exception PropertyReferenceException: No property <property> found for type <Entity>! and prevents the Spring context from running.

@Data
public class CommentProjection {

    @Value("#{target.user}")    
    private final User theUser; // throw PropertyReferenceException: No property theUser found for type Comment!
}

My demo project.

UPDATE

I've posted a bug report: DATAJPA-1186

UPDATE

It's not a bug, it's a feature.

Upvotes: 2

Related Questions