【问题标题】:Spring boot jpa / hibernate wrong column type encounter (json field)Spring boot jpa/hibernate 遇到列类型错误(json字段)
【发布时间】:2019-05-10 20:10:42
【问题描述】:

我正在使用 Spring Boot 将表映射到 POJO,但出现以下错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/mercadolibre/linters/db/config/DbaConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [linter_summary] in table [result]; found [json (Types#CHAR)], but expecting [varchar(255) (Types#VARCHAR)]

数据库中的字段linter_summary 是JSON 类型,而在我的pojo 上是一个字符串。我不明白为什么会出现这个错误,Java 中是否有用于 JSON 字段的特殊变量?

【问题讨论】:

    标签: java mysql json hibernate spring-boot


    【解决方案1】:

    添加这个 Maven 依赖项:

    <!-- https://mvnrepository.com/artifact/com.vladmihalcea/hibernate-types-52 -->
    <dependency>
        <groupId>com.vladmihalcea</groupId>
        <artifactId>hibernate-types-52</artifactId>
        <version>${hibernate-types.version}</version>
    </dependency>
    

    接下来,将这个注解添加到实体类中:

    @TypeDefs({
        @TypeDef(name = "json", typeClass = JsonStringType.class),
        @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
    })
    

    然后将其添加到列定义中:

    @Type( type = "json" )
    @Column( columnDefinition = "json" )
    

    其中@Typeorg.hibernate.annotations.Type

    解释见this article

    【讨论】:

    • 嗨 Eugen,但我得到 org.hibernate.boot.registry.classloading.spi.ClassLoadingException:无法加载类 [json]
    • @elcharrua 不,您可以简单地将@Lob 用于longtext
    • 非常感谢欧根
    • 您好,执行此操作后,出现错误无法解析符号“JsonStringType”和无法解析符号“JsonBinaryType”
    • 我也遇到了同样的错误。 JsonStringType 和 JsonBinaryType 无法解析。
    【解决方案2】:

    在某些情况下,如果您不构建 Web 服务器容器,请尝试添加

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-json</artifactId>
            </dependency>
    

    这有助于提供您可能需要的一些序列化功能。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2017-01-24
    相关资源
    最近更新 更多