在 Spring Boot JPA 中映射枚举和时间类型

Posted

技术标签:

【中文标题】在 Spring Boot JPA 中映射枚举和时间类型【英文标题】:Mapping Enum and Time types in Spring Boot JPA 【发布时间】:2021-03-05 09:18:12 【问题描述】:

这是我的堆栈跟踪,还有一行显示创建的课程对象

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.5.RELEASE)

2020-11-22 16:05:16.309  INFO 12924 --- [  restartedMain] pl.umcs.lessonwiz.LessonwizApplication   : Starting LessonwizApplication on DESKTOP-4VPS8T4 with PID 12924 (C:\Users\admin\IdeaProjects\lessonwiz\build\classes\java\main star
ted by admin in C:\Users\admin\IdeaProjects\lessonwiz)
2020-11-22 16:05:16.312  INFO 12924 --- [  restartedMain] pl.umcs.lessonwiz.LessonwizApplication   : No active profile set, falling back to default profiles: default
2020-11-22 16:05:16.356  INFO 12924 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-11-22 16:05:16.356  INFO 12924 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-11-22 16:05:16.914  INFO 12924 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-11-22 16:05:16.981  INFO 12924 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 59ms. Found 4 JPA repository interfaces.
2020-11-22 16:05:17.556  INFO 12924 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-11-22 16:05:17.566  INFO 12924 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-11-22 16:05:17.566  INFO 12924 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.39]
2020-11-22 16:05:17.672  INFO 12924 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-11-22 16:05:17.672  INFO 12924 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1316 ms
2020-11-22 16:05:17.717  INFO 12924 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-11-22 16:05:17.842  INFO 12924 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-11-22 16:05:18.118  INFO 12924 --- [  restartedMain] o.s.b.a.h2.H2ConsoleAutoConfiguration    : H2 console available at '/h2-console'. Database available at 'jdbc:postgresql://127.0.0.1:5432/postgres'
2020-11-22 16:05:18.166  INFO 12924 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-11-22 16:05:18.253  INFO 12924 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-11-22 16:05:18.301  INFO 12924 --- [         task-1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-11-22 16:05:18.338  WARN 12924 --- [  restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly confi
gure spring.jpa.open-in-view to disable this warning
2020-11-22 16:05:18.358  INFO 12924 --- [         task-1] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.22.Final
2020-11-22 16:05:18.526  INFO 12924 --- [         task-1] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations 5.1.0.Final
2020-11-22 16:05:18.578  WARN 12924 --- [  restartedMain] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2020-11-22 16:05:18.658  INFO 12924 --- [         task-1] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2020-11-22 16:05:18.689  INFO 12924 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-11-22 16:05:18.690  INFO 12924 --- [  restartedMain] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositoriesů
2020-11-22 16:05:19.658  INFO 12924 --- [         task-1] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-11-22 16:05:19.665  INFO 12924 --- [         task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-11-22 16:05:19.841  INFO 12924 --- [  restartedMain] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-11-22 16:05:19.848  INFO 12924 --- [  restartedMain] pl.umcs.lessonwiz.LessonwizApplication   : Started LessonwizApplication in 3.874 seconds (JVM running for 4.346)
Test method
Course(id=0, title=Title, start=16:05:19.853670100, end=16:05:19.853670100, day=FRIDAY, totalPlaces=40, semesterId=1, teacherId=1)
Hibernate:
    /* insert pl.umcs.lessonwiz.domain.Course
        */ insert
        into
            course
            (day, end_time, semester_id, start_time, teacher_id, title, total_places)
        values
            (?, ?, ?, ?, ?, ?, ?)
2020-11-22 16:05:19.909  WARN 12924 --- [  restartedMain] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 42804
2020-11-22 16:05:19.909 ERROR 12924 --- [  restartedMain] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: column "day" is of type days but expression is of type character varying
  Wskazˇwka: You will need to rewrite or cast the expression.
  Pozycja: 147
2020-11-22 16:05:19.926 ERROR 12924 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:281) ~[spring-orm-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255) ~[spring-orm-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528) ~[spring-orm-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:154) ~[spring-tx-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178) ~[spring-data-jpa-2.3.5.RELEASE.jar:2.3.5.RELE
ASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at com.sun.proxy.$Proxy93.save(Unknown Source) ~[na:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205) ~[spring-aop-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at com.sun.proxy.$Proxy62.save(Unknown Source) ~[na:na]
        at pl.umcs.lessonwiz.Test.test(Test.java:47) ~[main/:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
        at org.springframework.context.event.ApplicationListenerMethodAdapter.doInvoke(ApplicationListenerMethodAdapter.java:305) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.context.event.ApplicationListenerMethodAdapter.processEvent(ApplicationListenerMethodAdapter.java:190) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.context.event.ApplicationListenerMethodAdapter.onApplicationEvent(ApplicationListenerMethodAdapter.java:153) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:404) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:361) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.boot.context.event.EventPublishingRunListener.running(EventPublishingRunListener.java:108) ~[spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at org.springframework.boot.SpringApplicationRunListeners.running(SpringApplicationRunListeners.java:77) ~[spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:330) ~[spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at pl.umcs.lessonwiz.LessonwizApplication.main(LessonwizApplication.java:13) ~[main/:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
        at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.3.5.RELEASE.jar:2.3.5.RELEASE]
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
        at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:103) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:43) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3158) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3764) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:84) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:330) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:720) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:706) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
        at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:314) ~[spring-orm-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at com.sun.proxy.$Proxy81.persist(Unknown Source) ~[na:na]
        at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:554) ~[spring-data-jpa-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
        at org.springframework.data.repository.core.support.ImplementationInvocationMetadata.invoke(ImplementationInvocationMetadata.java:72) ~[spring-data-commons-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:382) ~[spring-data-commons-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:205) ~[spring-data-commons-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:550) ~[spring-data-commons-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:155) ~[spring-data-commons-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130) ~[spring-data-commons-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.3.5.RELEASE.jar:2.3.5.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367) ~[spring-tx-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) ~[spring-tx-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        ... 38 common frames omitted
Caused by: org.postgresql.util.PSQLException: ERROR: column "day" is of type days but expression is of type character varying
  Wskazˇwka: You will need to rewrite or cast the expression.
  Pozycja: 147
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2553) ~[postgresql-42.2.18.jar:42.2.18]
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2285) ~[postgresql-42.2.18.jar:42.2.18]
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:323) ~[postgresql-42.2.18.jar:42.2.18]
        at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:473) ~[postgresql-42.2.18.jar:42.2.18]
        at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:393) ~[postgresql-42.2.18.jar:42.2.18]
        at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:164) ~[postgresql-42.2.18.jar:42.2.18]
        at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:130) ~[postgresql-42.2.18.jar:42.2.18]
        at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-3.4.5.jar:na]
        at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.5.jar:na]
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
        ... 82 common frames omitted

2020-11-22 16:05:19.996  INFO 12924 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-11-22 16:05:19.997  INFO 12924 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2020-11-22 16:05:19.999  INFO 12924 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2020-11-22 16:05:20.006  INFO 12924 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.6.1/userguide/command_line_interface.html#sec:command_line_warnings

课程表:

CREATE TABLE course (
  id           serial,
  title        varchar(50) NOT NULL,
  start_time   time        NOT NULL,
  end_time     time        NOT NULL,
  day          days        NOT NULL,
  total_places integer     NOT NULL DEFAULT 0,
  semester_id  integer     NULL,
  teacher_id   integer     NULL,
  PRIMARY KEY (id)
);

我手动添加了一些记录并且它有效:

INSERT INTO course (title, start_time, end_time, day, total_places, semester_id, teacher_id)
VALUES ('Analiza matematyczna', '12:00:00', '13:30:00', 'MONDAY', 10, 1, 4),
       ('Programowanie obiektowe', '15:00:00', '16:00:00', 'MONDAY', 15, 1, 2);

课程实体:

package pl.umcs.lessonwiz.domain;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import pl.umcs.lessonwiz.domain.enumeration.Days;

import javax.persistence.*;
import java.sql.Time;

package pl.umcs.lessonwiz.domain;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import pl.umcs.lessonwiz.domain.enumeration.Days;

import javax.persistence.*;
import java.time.LocalTime;

@Entity
@Data
@NoArgsConstructor
public class Course

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    int id;

    @Column(name = "title")
    String title;

    @Column(name = "start_time")
    LocalTime start;

    @Column(name = "end_time")
    LocalTime end;

    @Enumerated(EnumType.STRING)
    @Column(name = "day")
    Days day;

    @Column(name = "total_places")
    int totalPlaces;

    @Column(name = "semester_id")
    int semesterId;

    @Column(name = "teacher_id")
    int teacherId;

    public Course(String title, LocalTime start, LocalTime end, Days day, int totalPlaces, int semesterId, int teacherId) 
        this.title = title;
        this.start = start;
        this.end = end;
        this.day = day;
        this.totalPlaces = totalPlaces;
        this.semesterId = semesterId;
        this.teacherId = teacherId;
    


此实体的存储库:

package pl.umcs.lessonwiz.infrastructure;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.umcs.lessonwiz.domain.Course;

@Repository
public interface CourseRepository extends JpaRepository<Course, Integer> 

枚举类型:

package pl.umcs.lessonwiz.domain.enumeration;

public enum Days

    FRIDAY, MONDAY, SATURDAY, SUNDAY, THURSDAY, TUESDAY, WEDNESDAY;


测试方法(添加新课程到数据库):

package pl.umcs.lessonwiz;

import lombok.SneakyThrows;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pl.umcs.lessonwiz.domain.Course;
import pl.umcs.lessonwiz.domain.Student;
import pl.umcs.lessonwiz.domain.StudentFactory;
import pl.umcs.lessonwiz.domain.Teacher;
import pl.umcs.lessonwiz.domain.enumeration.Days;
import pl.umcs.lessonwiz.infrastructure.CourseRepository;
import pl.umcs.lessonwiz.infrastructure.StudentRepository;
import pl.umcs.lessonwiz.infrastructure.TeacherRepository;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Date;


@Component
public class Test 

    @Autowired
    CourseRepository courseRepository;

    @Autowired
    StudentFactory studentFactory;

    @Autowired
    StudentRepository studentRepository;

    @EventListener(ApplicationReadyEvent.class)
    public void test()
    
        System.out.println("Test method");
        LocalTime time = LocalTime.now();
        Course course = new Course("Title", time, time, Days.FRIDAY, 40, 1, 1);
        System.out.println(course);

        //studentRepository.save(studentFactory.createStudent("TEST", "TEST", "TEST"));
        courseRepository.save(course);
    



看起来 hibernate 无法理解我的枚举类型。我使用 postgresql 数据库。如果有人可以查看我的代码并给我一些建议,我将非常感激。感谢您的回答。

【问题讨论】:

【参考方案1】:

只需将以下内容添加到您的 SQL 中:

CREATE CAST (character varying as days) WITH INOUT AS IMPLICIT;

这样,JPA 可以继续将 Java Enum 类型 Days 的对象转换为 SQL 类型“varchar”,正如您在 @Enumerated(STRING) 中所说的那样。 Postgres 会默默地将该 varchar 转换为它的 "days" 类型。

【讨论】:

【参考方案2】:

    我建议你使用 java 8 java.time.LocalTime 而不是 java.sql.Time

    根据documentation,如果要保存枚举值的名称,则应使用EnumType.STRING

@Enumerated(EnumType.STRING)
Days day;
    您应该明确指定以下字段的列名:
@Column(name = "start_time")
Time start;

@Column(name = "end_time")
Time end;
    见this article。修复
org.postgresql.util.PSQLException: ERROR: column "day" is of type days but expression is of type character varying

你应该使用hibernate custom type(你可以自己写或者使用hibernate-types库)或者干脆把day days NOT NULL列的定义改成day VARCHAR(10) NOT NULL这样的东西。

【讨论】:

1.更改为 LocalTime 但没有帮助。 3. 我有这个(@NoArgsConstructor 注释)我有相同的堆栈跟踪 尝试使用 EnumType.STRING 而不是EnumType.ORDINAL 我也这样做了,但没有帮助 请启用以下休眠配置属性:hibernate.show_sqlhibernate.format_sqlhibernate.use_sql_comments 并检查生成了什么 sql。 休眠:插入课程(day、end、semester_id、start、teacher_id、title、total_places)值(?、?、?、?、?、?、?)

以上是关于在 Spring Boot JPA 中映射枚举和时间类型的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot JPA @JoinTable 与现有映射表忽略 @GeneratedValue

在 Spring Boot jpa 中将多个外键映射到同一个主键

Spring boot JPA - 延迟加载不适用于一对一映射

可以将@Id添加到映射到Spring boot Jpa中没有主键列的表的实体吗?

Spring boot之 JPA/Hibernate/Spring Data

spring boot jpa中的多对一映射中的外键未在子表中更新