【问题标题】:Is there a way to use Generated Query Methods on Enum?有没有办法在枚举上使用生成的查询方法?
【发布时间】:2021-08-03 00:07:57
【问题描述】:

我正在尝试使用 Spring 中的自动生成查询方法通过使用枚举来获取一些数据,例如:

public enum AnimalType {
    MAMMAL,
    INSECT
}

但是有两种错误场景

1 - 没有检索到任何内容;

2 - 抛出异常:

Error creating bean with name 'AnimalRepository' defined in com.example.demo.core.animal.AnimalRepository 
defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: 
Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: 
No property AnimalType found for type Insect! Traversed path: Animal.animalType.

在我的一项测试中,我用字符串替换了 Enum,它运行良好。

类是这样的:

public class Animal {

    @Id
    private String id;
    private String description;
    private String color;
    private AnimalType animalType;
    //GET SET
}

和存储库

@Repository
public interface AnimalRepository extends MongoRepository<Animal, String>{

   // SOME METHODS HERE

}

我已经试过了:

Optional<Animal> findAnimalByIdAndAnimalTypeLike(String id, AnimalType type);

Optional<Animal> findAnimalByIdAndAnimalTypeInsect(String id);

Optional<Animal> findAnimalByIdAndAnimalType_Insect(String id);

Optional<Animal> findAnimalByIdAndAnimalType_INSECT(String id);

【问题讨论】:

  • 很可能,您的数据库包含Insect 的数据,应将其大写为INSPECT。反之亦然 -> 你的枚举应该包含 Inspect

标签: java spring-boot mongodb-query nosql repository


【解决方案1】:

您误导了 jpa 约定查询的变量名称。您的变量名称是类型。所以你的查询应该是这样的:

Optional&lt;Animal&gt; findAnimalByIdAndTypeLike(String id, AnimalType type);

【讨论】:

  • 哦,对不起,我在这里手动输入了整个代码,这不是我所面临的真实上下文,我只是用 Animal 替换了真实的交易。但是感谢您注意到类型错误。
  • 我可以在我的机器上运行你的例子。你现在的错误是什么?
  • 您可能忘记将动物类注释为@Document(collection = "animal")
猜你喜欢
  • 2015-06-07
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 2015-03-17
  • 1970-01-01
  • 2021-06-02
相关资源
最近更新 更多