【问题标题】:How can I use Spring Data Projection with a Transient property?如何将 Spring Data Projection 与 Transient 属性一起使用?
【发布时间】:2016-06-12 07:21:52
【问题描述】:

我将 Spring Data 与 MongoDB 以及其中一个存储库的投影接口一起使用。
问题是我的实体上的瞬态字段不被识别为模型上的有效属性,因为它不是查询结果的一部分。 [假设]

有解决办法吗?

例子-

// Entity class fields 
@JsonProperty(access=Access.WRITE_ONLY)
private String password;
@Id
private String username;
private String displayName;
@DBRef
private Set<EmailAddress> emailAddresses = new HashSet<>();
@DBRef
@NotEmpty
private EmailAddress primaryEmailAddress;
private boolean hidePrimaryEmailAddress;
private String firstName;
private String lastName;
@JsonTypeInfo(use = com.fasterxml.jackson.annotation.JsonTypeInfo.Id.NONE)
private Set<Role> authorities;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
private boolean enabled;
@Transient
private String gravatarUrl;

.....

// Spring Data Projection 
public interface ProfileProjection {
  @Value("#{target.primaryEmailAddress.emailAddress}")
  String getEmailAddress();
  String getUsername();
  String getDisplayName();
  String getGravatarUrl();
}  

// Repository
public interface UserRepository extends ExtendedMongoRepository<SproutUser, String> {
    ProfileProjection findFirstByUsername(String username);
}  

例外-

No property gravatarUrl found on savantly.sprout.domain.SproutUser!

【问题讨论】:

    标签: java mongodb spring-data projection


    【解决方案1】:

    我使用 SPEL 来调用 getter,而不是直接依赖于字段。

    public interface ProfileProjection {
        @Value("#{target.primaryEmailAddress.emailAddress}")
        String getEmailAddress();
        String getPrimaryEmailAddress();
        String getUsername();
        String getDisplayName();
        @Value("#{target.getGravatarUrl()}")
        String getGravatarUrl();
    }
    

    【讨论】:

    • 工作就像一个魅力!就我而言,在我的实体中,我有 @Transient PLUS 我正在使用 Lombok:“@Transient @Setter(AccessLevel.NONE) private String simpleName;”
    猜你喜欢
    • 1970-01-01
    • 2021-07-27
    • 2014-08-16
    • 2012-05-10
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 2014-03-10
    • 2017-07-29
    相关资源
    最近更新 更多