Java 当在复合键中使用JPA AttributeConverter时,在Spring数据/hibernate查询中不受尊重

Java 当在复合键中使用JPA AttributeConverter时,在Spring数据/hibernate查询中不受尊重,java,hibernate,jpa,enums,spring-data,Java,Hibernate,Jpa,Enums,Spring Data,这是我的枚举: public enum FooBarType { Foo, Bar; @javax.persistence.Converter public static class Converter implements AttributeConverter<FooBarType, String> { @Override public String conve

这是我的枚举:

    public enum FooBarType {
        Foo,
        Bar;

        @javax.persistence.Converter
        public static class Converter implements AttributeConverter<FooBarType, String> {
            @Override
            public String convertToDatabaseColumn(FooBarType t) {
                return t.toString();
            }

            @Override
            public FooBarType convertToEntityAttribute(String s) {
                for (FooBarType value : FooBarType.values()) {
                    if (value.name().equalsIgnoreCase(s)) {
                        return value;
                    }
                }

                throw new IllegalArgumentException("Invalid value for enum: " + s);
            }
        }
    }
和我的存储库:

public interface FooBarRepository extends Repository<FooBar, FooBar.PrimaryKey> {
    FooBar getByIdAndFooBarType(String id, FooBarType fooBarType);
}
public interface FooBarRepository extends Repository<FooBar, FooBar.PrimaryKey> {
    FooBar getByIdAndFooBarType(String id, FooBarType foobar);
}
public interface FooBarRepository extends Repository<FooBar, FooBar.PrimaryKey> {
    FooBar getByCompositeKey(FooBar.PrimaryKey compositeKey);
}
当我测试
getByIdAndFooBarType(“someId”,FooBarType.Foo)
方法时,会引发以下异常:

org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.GenericJDBCException: could not execute query; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute query
        at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:418)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:418)
        at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
        at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:131)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
        at com.sun.proxy.$Proxy49.getByUserIdAndAppType(Unknown Source)
        at com.treeboxsolutions.services.onCredentialService.databaseProviders.dataAccessLayer.repositories.CurrentCredentialRepositoryTest.saveShouldCorrectlySave(CurrentCredentialRepositoryTest.java:49)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
        at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
        at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
        at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
        at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute query
        at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
        at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
        at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:524)
        at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:71)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:364)
        at com.sun.proxy.$Proxy50.getSingleResult(Unknown Source)
        at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:206)
        at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:78)
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:100)
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:91)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:462)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:440)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
        ... 43 more
Caused by: org.hibernate.exception.GenericJDBCException: could not execute query
        at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
        at org.hibernate.loader.Loader.doList(Loader.java:2557)
        at org.hibernate.loader.Loader.doList(Loader.java:2540)
        at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
        at org.hibernate.loader.Loader.list(Loader.java:2365)
        at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:497)
        at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
        at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:236)
        at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1300)
        at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
        at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:573)
        at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:495)
        ... 64 more
Caused by: java.sql.SQLException: Invalid value for getInt() - 'Foo'
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
        at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2705)
        at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2793)
        at org.hibernate.type.EnumType$OrdinalEnumValueMapper.getValue(EnumType.java:372)
        at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:107)
        at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:127)
        at org.hibernate.type.AbstractType.hydrate(AbstractType.java:106)
        at org.hibernate.type.ComponentType.hydrate(ComponentType.java:641)
        at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:785)
        at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:721)
        at org.hibernate.loader.Loader.processResultSet(Loader.java:953)
        at org.hibernate.loader.Loader.doQuery(Loader.java:921)
        at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
        at org.hibernate.loader.Loader.doList(Loader.java:2554)
        ... 74 more
Spring数据/hibernate查询生成器似乎不支持
@Convert
属性。 如果我放置
@Enumerated
属性,则会忽略
@Convert
属性,并引发预期的异常。异常基本上表示它无法将“FOO”映射回FooBarType(由于区分大小写)



更新!此问题仅影响复合主键
使用
@Converter
注释时,常规列的工作方式与预期的一样。您应该尝试这样枚举:

@Id
@Enumerated(EnumType.STRING)
@Column(name = "foobar")
public FooBarType fooBarType;
而您的存储库:

public interface FooBarRepository extends Repository<FooBar, FooBar.PrimaryKey> {
    FooBar getByIdAndFooBarType(String id, FooBarType fooBarType);
}
public interface FooBarRepository extends Repository<FooBar, FooBar.PrimaryKey> {
    FooBar getByIdAndFooBarType(String id, FooBarType foobar);
}
public interface FooBarRepository extends Repository<FooBar, FooBar.PrimaryKey> {
    FooBar getByCompositeKey(FooBar.PrimaryKey compositeKey);
}
公共接口foobarepository扩展存储库{
FooBar getByIdAndFooBarType(字符串id,FooBarType FooBar);
}

出于一个非常奇怪的原因,如果我选择使用
@embedded
@EmbeddedId
声明复合键(而不是使用
@IdClass
),则@Convert注释是值得尊敬的。 在我看来,这是一种行为上的脱节

工作代码:

public enum FooBarType {
    Foo,
    Bar;

    @javax.persistence.Converter
    public static class Converter implements AttributeConverter<FooBarType, String> {
        @Override
        public String convertToDatabaseColumn(FooBarType t) {
            return t.toString();
        }

        @Override
        public FooBarType convertToEntityAttribute(String s) {
            for (FooBarType value : FooBarType.values()) {
                if (value.name().equalsIgnoreCase(s)) {
                    return value;
                }
            }

            throw new IllegalArgumentException("Invalid value for enum: " + s);
        }
    }
}
和我的存储库:

public interface FooBarRepository extends Repository<FooBar, FooBar.PrimaryKey> {
    FooBar getByIdAndFooBarType(String id, FooBarType fooBarType);
}
public interface FooBarRepository extends Repository<FooBar, FooBar.PrimaryKey> {
    FooBar getByIdAndFooBarType(String id, FooBarType foobar);
}
public interface FooBarRepository extends Repository<FooBar, FooBar.PrimaryKey> {
    FooBar getByCompositeKey(FooBar.PrimaryKey compositeKey);
}
公共接口foobarepository扩展存储库{
FooBar getByCompositeKey(FooBar.PrimaryKey compositeKey);
}

您不能在同一字段上使用
Convert
Id
注释,也不能使用
Convert
枚举
。如
@Converter
文档所示,使用
EmbeddedId

请注意,不会转换Id属性、版本属性、关系属性和显式注释为枚举或时态(或通过XML指定)的属性


请参阅:JSR-338,第11.1.10章转换注释,第438页。

如果使用@enumerated注释枚举,则如果案例不正确且出现其他异常,则从db到实体的转换将失败。我想在这里做一个不区分大小写的转换器。你能给你的帖子添加一个例外吗?没问题。已添加@Enumerated的预期异常。问题是在hibernate的JIRA中创建的。影响4.3.11.Final和5.1.0.Final。林克:我想从其他答案中已经很清楚了。你知道为什么不能在同一字段上使用
Convert
Id
,也不能使用
Convert
枚举的
注释吗?添加了
@Converter
的摘录。还向JSR 338添加了源代码