为啥我的带有@EmbeddedId 的实体不能在其对应的@Embeddable 类中使用LocalDateTime?

Posted

技术标签:

【中文标题】为啥我的带有@EmbeddedId 的实体不能在其对应的@Embeddable 类中使用LocalDateTime?【英文标题】:Why can't my entity with an @EmbeddedId use the LocalDateTime in it's corresponding @Embeddable Class?为什么我的带有@EmbeddedId 的实体不能在其对应的@Embeddable 类中使用LocalDateTime? 【发布时间】:2020-01-14 07:05:18 【问题描述】:

我实现了一个使用@EmbeddedId 的实体。 @Embeddable - 类将数据类型 LocalDateTime 用于两个组合键属性之一。当我通过控制器收集严重属性时,我收到java.util.Date 预期的错误。 我正在使用:kotlin("plugin.jpa") version "1.2.71"Gradle: org.hibernate:hibernate-core:5.3.10.Finalmysql - Server

我设法确定在我实现复合键时发生了错误。

更新:当我创建一个完全不同的实体(也使用 LocalDateTime)时会发生错误。如果我摆脱了复合键(并且只对@Id 使用一个属性),则不会出现错误。但是一旦我实现复合键,就会发生错误。这让我很困惑,因为我不知道为什么复合键会影响其他实体

import java.io.Serializable
import javax.persistence.EmbeddedId
import javax.persistence.Entity

@Entity(name = "entity")
class SensorHistory(@EmbeddedId val entityId: EntityId,
                    val value: Float) : Serializable 

import java.io.Serializable
import java.time.LocalDateTime
import javax.persistence.Embeddable

@Embeddable
class EntityId(val timestamp: LocalDateTime,
               val sensor_id: Long) :
        Serializable 

这是控制器正在使用的存储库的一部分:

@Query("SELECT COALESCE(SUM(value),0) FROM entity WHERE sensor_id = ?1 AND timestamp > ?2")
    fun countLitersSince(sensor_id: Long?, since: LocalDateTime): Float

这是堆栈跟踪:

org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [2000-01-01T12:00:01] did not match expected type [java.util.Date (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [2000-01-01T12:00:01] did not match expected type [java.util.Date (n/a)]

    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:373)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:144)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$ExposeRepositoryInvocationInterceptor.invoke(CrudMethodMetadataPostProcessor.java:364)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.MethodInvocationValidator.invoke(MethodInvocationValidator.java:99)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy109.countLitersSince(Unknown Source)
    at de.iteratec.sodadispenser.controller.SodaDispenserController.getAllSodaDispensers(SodaDispenserController.kt:39)
    at de.iteratec.sodadispenser.tests.controller.SodaDispenserControllerTest.check(SodaDispenserControllerTest.kt:121)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    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.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    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:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    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:190)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    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.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.IllegalArgumentException: Parameter value [2000-01-01T12:00:01] did not match expected type [java.util.Date (n/a)]
    at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:54)
    at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:27)
    at org.hibernate.query.internal.QueryParameterBindingImpl.validate(QueryParameterBindingImpl.java:90)
    at org.hibernate.query.internal.QueryParameterBindingImpl.setBindValue(QueryParameterBindingImpl.java:55)
    at org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:511)
    at org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:106)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:403)
    at com.sun.proxy.$Proxy126.setParameter(Unknown Source)
    at org.springframework.data.jpa.repository.query.QueryParameterSetter$NamedOrIndexedQueryParameterSetter.lambda$setParameter$5(QueryParameterSetter.java:124)
    at org.springframework.data.jpa.repository.query.QueryParameterSetter$ErrorHandling$1.execute(QueryParameterSetter.java:175)
    at org.springframework.data.jpa.repository.query.QueryParameterSetter$NamedOrIndexedQueryParameterSetter.setParameter(QueryParameterSetter.java:124)
    at org.springframework.data.jpa.repository.query.ParameterBinder.lambda$bind$0(ParameterBinder.java:79)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at java.base/java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1083)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:79)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:74)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:96)
    at org.springframework.data.jpa.repository.query.AbstractStringBasedJpaQuery.doCreateQuery(AbstractStringBasedJpaQuery.java:93)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:210)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:221)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    ... 54 more


【问题讨论】:

我会说在你的数据库中你想要一个日期类型。 另一个实体使用 LocalDateTime,我没有遇到任何问题。 您确定错误出在这部分代码中吗?在您的错误中,我看到您没有使用对 java.util.Date 的引用。我还在您的堆栈跟踪中看到了对countLitersSince 的引用。你能显示那个代码吗? @g00glen00b 我已将其添加到原始帖子中 感谢您添加代码。你不应该把你的查询改成SELECT COALESCE(SUM(value),0) FROM entity WHERE entity.entityId.sensor_id = ?1 AND entity.entityId.timestamp > ?2吗? 【参考方案1】:

您问题中的堆栈跟踪表明错误在您的存储库调用com.sun.proxy.$Proxy109.countLitersSince 中。原因是查询无效,因为timestampsensor_id 以这种方式存在。

如果您使用 Spring Data JPA,则默认查询语言是 JPQL,它代表 JPA 查询语言。这意味着查询应该遵循您的实体声明:

虽然您的实体名称通常为 SensorHistory,但您对其进行了重命名,因此应该像以前一样从 entity 查询。 此外,它使用了更加面向对象的方法。由于valueentity 的一部分,它应该变成entity.valuesensor_idtimestamp 也应如此。这两个字段都是 entity.entityId 的一部分,也应该被替换。
@Query("select coalesce(sum(entity.value), 0) from entity where entity.entityId.sensor_id = ?1 and entity.entityId.timestamp > ?2")
fun countLitersSince(sensor_id: Long?, since: LocalDateTime): Float

或者,如果您想使用纯 SQL,您可以将 nativeQuery 设置为 true

@Query(value = "SELECT COALESCE(SUM(value),0) FROM entity WHERE sensor_id = ?1 AND timestamp > ?2", nativeQuery = true) // Add nativeQuery
fun countLitersSince(sensor_id: Long?, since: LocalDateTime): Float

我不确定为什么这个错误没有更清楚。通常它应该抛出一个异常,告诉你它不知道如何处理“entity”、“timestamp”或“sensor_id”,但它设法找到一个名为entity 的实体,其类型为timestamp java.util.Date.


从 cmets 看来,您将实体命名为 StatusHistory,而您的表命名为 status_history。如果您想使用 JPQL,您可以将实体更改为如下所示:

@Entity
@Table(name = "sensor_history")
class SensorHistory(@EmbeddedId val id: SensorHistoryId,
                    val value: Float) : Serializable 


@Embeddable
class SensorHistoryId(val timestamp: LocalDateTime,
                      @Column(name = "sensor_id") val sensorId: Long) : Serializable 

然后你应该可以使用这样的查询:

@Query("select coalesce(sum(sh.value), 0) from SensorHistory sh where sh.id.sensorId = ?1 and sh.id.timestamp > ?2")
fun countLitersSince(sensorId: Long?, since: LocalDateTime): Float

使用 @Table@Column 注释,您可以在 Kotlin 类中正确使用替代名称。

【讨论】:

谢谢先生! nativeQuery = true 的方法对我有用。虽然我不知道如何应用其他方法。我的真实实体是:SensorHistory(而不是 Entity)/sensor_history(在数据库中)和 SensorHistoryId(而不是 EntityId)。查询应该是什么样子? 我在答案的底部添加了一个示例。

以上是关于为啥我的带有@EmbeddedId 的实体不能在其对应的@Embeddable 类中使用LocalDateTime?的主要内容,如果未能解决你的问题,请参考以下文章

使用 @EmbeddedId 映射时出现 Eclipse 错误

将 @EmbeddedId 与 JpaRepository 一起使用

JPA @EmbeddedId 未生成序列

我应该使用哪个注释:@IdClass 或 @EmbeddedId

为啥我不能更新核心数据实体属性的布尔值?

带有@EmbeddedId 和@Embeddable 的EclipseLink 组合键