Spring CriteriaBuilder 按名称搜索枚举

Dan*_*aub 6 java enums spring hibernate jpa

当我尝试Specification在我的数据库中使用他的名字搜索 enum 时Spring @Repository,我收到以下异常:

Caused by: java.lang.IllegalArgumentException: Parameter value [HELLO] did not match expected type [application.springEnum.Hello (n/a)]
Run Code Online (Sandbox Code Playgroud)

但是在数据库中,枚举保存为VARCHAR(255)为什么我可以用 搜索枚举String,为什么需要通过枚举类型?

DTO类

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DTO {
    @Id
    private String id;
    @Enumerated(EnumType.STRING)
    private Hello helloEnum; // My Enum
}
Run Code Online (Sandbox Code Playgroud)

数据库连接器

@Repository
public interface Connector extends JpaRepository<DTO, String>, JpaSpecificationExecutor<DTO> {
}
Run Code Online (Sandbox Code Playgroud)

起动机

@Component
public class Starter {
    @Autowired
    private Connector connector;

    @PostConstruct
    public void init(){
        // Create DTO entity
        DTO dto = DTO.builder()
                .id(UUID.randomUUID().toString())
                .helloEnum(Hello.HELLO)
                .build();
        // Save the entity in the db
        connector.save(dto);

        // Search by the name, here I get the excpetion
        List<DTO> result = connector.findAll((root, query, cb) ->
                cb.equal(root.get("helloEnum"), "HELLO")
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

我很感激你的解释。

J-A*_*lex 8

你试图比较EnumString

试试这个方法:

List<DTO> result = connector.findAll((root, query, cb) ->
                cb.equal(root.get("helloEnum"), Hello.HELLO);
Run Code Online (Sandbox Code Playgroud)

我将尝试提供一些解释为什么会发生这种情况。HibernateResultSet使用.ClassReflection

观察堆栈跟踪你会看到类似的内容:

org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:54) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final] 在 org.hibernate.query.spi.QueryParameterBindingValidator.validate (QueryParameterBindingValidator.java:27) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final] 在 org.hibernate.query.internal.QueryParameterBindingImpl.validate(QueryParameterBindingImpl.java:90) ~[hibernate- core-5.2.16.Final.jar:5.2.16.Final] 在 org.hibernate.query.internal.QueryParameterBindingImpl.setBindValue(QueryParameterBindingImpl.java:55) ~[hibernate-core-5.2.16.Final.jar:5.2 .16.Final] 在 org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:486) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final] 在 org.hibernate.query .internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:104) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]

Hibernate 在设置参数之前执行一系列验证。

这是初始化根本原因的最后一个方法Exception

public <P> void validate(Type paramType, Object bind, TemporalType temporalType) {
        if ( bind == null || paramType == null ) {
            // nothing we can check
            return;
        }
        final Class parameterType = paramType.getReturnedClass();
        if ( parameterType == null ) {
            // nothing we can check
            return;
        }

        if ( Collection.class.isInstance( bind ) && !Collection.class.isAssignableFrom( parameterType ) ) {
            // we have a collection passed in where we are expecting a non-collection.
            //      NOTE : this can happen in Hibernate's notion of "parameter list" binding
            //      NOTE2 : the case of a collection value and an expected collection (if that can even happen)
            //          will fall through to the main check.
            validateCollectionValuedParameterBinding( parameterType, (Collection) bind, temporalType );
        }
        else if ( bind.getClass().isArray() ) {
            validateArrayValuedParameterBinding( parameterType, bind, temporalType );
        }
        else {
            if ( !isValidBindValue( parameterType, bind, temporalType ) ) {
                throw new IllegalArgumentException(
                        String.format(
                                "Parameter value [%s] did not match expected type [%s (%s)]",
                                bind,
                                parameterType.getName(),
                                extractName( temporalType )
                        )
                );
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

private static boolean isValidBindValue(Class expectedType, Object value, TemporalType temporalType)有一堆检查的方法会返回false,因为您期望的类型是class com.whatever.Hello,要检查的值是HELLO什么String,但Enum类型 和String不兼容!

Enum如果您在搜索条件中输入正确的内容,验证将通过,因为private static boolean isValidBindValue(Class expectedType, Object value, TemporalType temporalType)包含isInstance将通过的检查:

else if ( expectedType.isInstance( value ) ) {
    return true;
}
Run Code Online (Sandbox Code Playgroud)

在完成所有检查之后,Hibernate 会从中提取值ResultSet并构建,在这种特殊情况下,会使用反射来获取List的元素。List

  • 有没有办法将标准构建器类似方法与枚举一起使用? (2认同)