【问题标题】:Spring jpa Entity field List<String> to postgre array filed not workingSpring jpa Entity field List<String> 到 postgres 数组字段不起作用
【发布时间】:2021-12-07 17:19:24
【问题描述】:

我有一个这样的实体:

@Entity
@Data
public class Cat {
  @Id
  private String catId;
  private String catName;
  private List<String> favFoods;
}

当我启动我的 Spring boot 时,它显示了这个错误:

Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.List

在启动应用程序之前,我在 DB 中删除了表 Cat 我的 yml 设置是:

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/localtest
    username: catuser
    password:
  jpa:
    show-sql: false
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
        format_sql: true

如果我注释掉 List 字段,一切正常。 是否需要添加任何注释来解决此问题?

谢谢

【问题讨论】:

    标签: java spring postgresql spring-boot jpa


    【解决方案1】:

    也可以使用下面的代码sn-p

        @ElementCollection
        @CollectionTable(name = "my_list", joinColumns = @JoinColumn(name = 
            "id"))
        @Column(name = "list")
        List<String> favFoods;
    

    here

    【讨论】:

      【解决方案2】:

      你必须告诉 Hibernate how to map the list,用 @TypeDef(name = "list-array",typeClass = ListArrayType.class) 注释你的类并用 @Type(type = "list-array") 注释列表,即:

      @Entity
      @Data
      @TypeDef(
          name = "list-array",
          typeClass = ListArrayType.class
      )
      public class Cat {
        @Id
        private String catId;
      
        private String catName;
      
        @Type(type = "list-array")
        private List<String> favFoods;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-03
        • 2020-01-20
        • 1970-01-01
        • 1970-01-01
        • 2012-12-26
        • 2012-04-04
        • 1970-01-01
        相关资源
        最近更新 更多