从Spring Boot 1.5.10升级到2.0 Spring Data Mongo @Query

4

我需要将Spring Boot 1.5.10迁移到2.0,但遇到了一个问题。使用@Query注解的查询语句不能再正常工作。在1.5.10中,这些查询语句可以正常运行。以下是其中一个查询语句与实体:

@Document(collection = "credentials")
public class Credentials implements Serializable, Comparable<Credentials>
{

    private static final long serialVersionUID = -921533822040690113L;

    @Id
    private UUID id;

    @Indexed
    @Field("userId")
    private UUID userId;

    @Field("access")
    private List<Access> access;

    @Field("roles")
    private List<String> roles;

    /**
     * @return the id
     */
    public UUID getId()
    {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(UUID id)
    {
        this.id = id;
    }

    /**
     * @return the userId
     */
    public UUID getUserId()
    {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(UUID userId)
    {
        this.userId = userId;
    }

    /**
     * @return the access
     */
    public List<Access> getAccess()
    {
        return access;
    }

    /**
     * @param access the access to set
     */
    public void setAccess(List<Access> access)
    {
        this.access = access;
    }

    /**
     * @return the roles
     */
    public List<String> getRoles()
    {
        return roles;
    }

    /**
     * @param roles the roles to set
     */
    public void setRoles(List<String> roles)
    {
        this.roles = roles;
    }

    /**
     *
     */
    public Credentials()
    {}

这是您需要翻译的内容:

这个查询是:

public interface ICredentialsRepository extends MongoRepository<Credentials, UUID>
{

    /**
     * This query finds the credentials by userId
     * @param userId user identification
     * @return Credentials object
     */
    @Query("{ 'userId' : ?0}")
    Credentials retrieveWithUserId(UUID userId);
}

运行时,我收到了错误提示。
com.mongodb.MongoQueryException: Query failed with error code 2 and error message 'unknown operator: $uuid' on server

再次强调,这在Spring Boot 1.5.10中完美运行。该项目包含spring-boot-starter-data-mongodb-2.0.0和spring-boot-configuration-processor-2.0.0。


为什么你使用字符串查询而不是查询派生(findByUserId(UUID))?字符串值被序列化为BSON/JSON,MongoDB的JSON编码器创建$uuid: … - mp911de
查询派生确实有效。对于这个例子,我可以使用它。然而,我所有其他的“@Query”操作都出现了相同的错误。例如:“@Query('{ 'institutionId':?0,'startDate':{'$gte':?1},'dateArchived':null}')”也会出现相同的错误。institutionId是UUID,但不是主键“_id”。 - Russell Collins
将UUID更改为字符串会导致查询不再返回之前正确的记录。请保留原来的UUID格式以获取正确的查询结果。 - Russell Collins
1个回答

0
这是因为您的UUID不是实体/文档类型。您应该在UUID类上使用@Document,以及在Credentials类中使用@Embedded和@Embeddebable来引用UUID类和UUID引用。

只是为了明确,UUID是Java JDK的一部分,它是MongoDB提供的GUID的表示。我将在对象声明上尝试@Embeddable。 - Russell Collins
1
好的,那个"@Embedded"解决方案不起作用。有趣的是,"@Id"对UUID没有问题。它只与"@Query"注释有问题。对于这个问题,如果我删除"@Query"注释并将方法重命名为findByUserId,它就可以工作了。应用程序中还有其他查询也无法工作。它们出现了相同类型的问题。 - Russell Collins

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接