如何在内存数据库脚本中指定h2的字符编码?

问题描述 投票:0回答:2

我在 JPA 测试课中遇到字符编码问题。

在我的h2内存数据库中我有这个插入查询

INSERT INTO MYTABLE (ID,FIELD1,FIELD2) VALUES (100,'ABC','Réclamation');

(请注意“Réclamation”中的“é”字样)

在我的 JUnit 测试中,我尝试断言 FIELD2 列的值等于“Réclamation”(如您所见)

但失败并出现以下错误:

org.junit.ComparisonFailure:预期:R[é]clamation 但是 是:R[�]鼓掌

我想知道是否有办法在 persistence.xml 文件中指定字符编码(也许?或其他地方)

这是我的 persistence.xml 测试文件:

<?xml version="1.0" encoding="UTF-8"?>
<persistence
    version="2.1"
    xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

    <persistence-unit name="myTestPU">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>com.myproject.myclass1</class>
        <class>com.myproject.myclass2</class>
        <properties>
            <property
                name="javax.persistence.schema-generation.database.action"
                value="none" />
            <property
                name="javax.persistence.sharedCache.mode"
                value="ENABLE_SELECTIVE" />
            <property
                name="javax.persistence.jdbc.url"
                value="jdbc:h2:mem:test;INIT=RUNSCRIPT FROM 'classpath:ddl/schema.sql'\;RUNSCRIPT FROM 'classpath:ddl/data.sql'" />
            <property
                name="javax.persistence.jdbc.driver"
                value="org.h2.Driver" />
            <property
                name="hibernate.dialect"
                value="org.hibernate.dialect.H2Dialect" />
            <property
                name="hibernate.show_sql"
                value="true" />
            <property
                name="hibernate.format_sql"
                value="true" />
        </properties>
    </persistence-unit>
</persistence>

我已经尝试过这些解决方案:

  • 在 persistence.xml 测试文件中添加以下属性:

    <property
        name="hibernate.connection.characterEncoding"
        value="utf8" />
    <property
        name="hibernate.connection.useUnicode"
        value="true" />
    <property
        name="hibernate.connection.charSet"
        value="UTF-8" />
    
  • 在我的 URL 属性中添加

    ?useUnicode=yes&amp;characterEncoding=UTF-8

他们都没有为我工作...

注意:我没有在我的应用程序中使用 spring 框架

jpa h2 persistence.xml jsr
2个回答
1
投票

我在 import.sql 文件中插入了查询,但这些值的编码不正确。 添加属性

<property name="hibernate.hbm2ddl.charset_name" value="UTF-8" />
帮我修好了。

如果你有一个旧版本的休眠(显然是 5.2.3 之前的版本),也许可以尝试这个线程中的其他解决方案: Hibernate/JPA import.sql utf8 字符损坏


0
投票

如果您使用带有@SpringBootTest 注释的 Spring Boot 测试,那么 H2 数据库应该使用在您的 JVM 参数中传递的任何编码(如果没有传递,那么它将使用环境默认值)。在 Spring Boot 环境中,您可以在 POM 中使用以下代码将编码更改为 UTF-8:

<properties>
    <spring-boot.run.jvmArguments>-Dfile.encoding=UTF-8</spring-boot.run.jvmArguments>
</properties>

还要确保您正在读入数据库的文件(包含 SQL 插入的文件)与您的环境采用相同的编码。

© www.soinside.com 2019 - 2024. All rights reserved.