有没有办法在枚举上使用生成的查询方法?

Is there a way to use Generated Query Methods on Enum?

我正在尝试使用 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,它工作正常。

class 类似于:

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);

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

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