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

Sin*_*DEM 5 jpa h2 persistence.xml jsr

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

\n\n

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

\n\n
INSERT INTO MYTABLE (ID,FIELD1,FIELD2) VALUES (100,\'ABC\',\'R\xc3\xa9clamation\');\n
Run Code Online (Sandbox Code Playgroud)\n\n

(请注意“R\xc3\xa9clamation”中的“\xc3\xa9”字符)

\n\n

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

\n\n

但它失败并出现以下错误:

\n\n
\n

org.junit.ComparisonFailure:预期:R[\xc3\xa9]clamation,但\n是:R[\xef\xbf\xbd]clamation

\n
\n\n

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

\n\n

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

\n\n
<?xml version="1.0" encoding="UTF-8"?>\n<persistence\n    version="2.1"\n    xmlns="http://xmlns.jcp.org/xml/ns/persistence"\n    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence\n             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">\n\n    <persistence-unit name="myTestPU">\n        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>\n        <class>com.myproject.myclass1</class>\n        <class>com.myproject.myclass2</class>\n        <properties>\n            <property\n                name="javax.persistence.schema-generation.database.action"\n                value="none" />\n            <property\n                name="javax.persistence.sharedCache.mode"\n                value="ENABLE_SELECTIVE" />\n            <property\n                name="javax.persistence.jdbc.url"\n                value="jdbc:h2:mem:test;INIT=RUNSCRIPT FROM \'classpath:ddl/schema.sql\'\\;RUNSCRIPT FROM \'classpath:ddl/data.sql\'" />\n            <property\n                name="javax.persistence.jdbc.driver"\n                value="org.h2.Driver" />\n            <property\n                name="hibernate.dialect"\n                value="org.hibernate.dialect.H2Dialect" />\n            <property\n                name="hibernate.show_sql"\n                value="true" />\n            <property\n                name="hibernate.format_sql"\n                value="true" />\n        </properties>\n    </persistence-unit>\n</persistence>\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

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

    \n\n
    <property\n    name="hibernate.connection.characterEncoding"\n    value="utf8" />\n<property\n    name="hibernate.connection.useUnicode"\n    value="true" />\n<property\n    name="hibernate.connection.charSet"\n    value="UTF-8" />\n
    Run Code Online (Sandbox Code Playgroud)
  • \n
  • 添加?useUnicode=yes&amp;characterEncoding=UTF-8我的 URL 属性

  • \n
\n\n

他们都不为我工作...

\n\n

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

\n

小智 1

我在 import.sql 文件中插入查询,并且这些值的编码不正确。添加属性 <property name="hibernate.hbm2ddl.charset_name" value="UTF-8" /> 为我解决了这个问题。

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