【发布时间】:2019-04-15 13:17:38
【问题描述】:
我在 JPA 测试类中遇到字符编码问题。
在我的 h2 in memory database 我有这个 insert query :
INSERT INTO MYTABLE (ID,FIELD1,FIELD2) VALUES (100,'ABC','Réclamation');
(请注意“Reclamation”中的“é”字符)
在我的 JUnit 测试中,我尝试断言 FIELD2 列的值等于“Réclamation”(如您所见)
但它失败并出现以下错误:
org.junit.ComparisonFailure:预期:R[é]clamation 但 是:R[�]clamation
我想知道是否有办法在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