眾所周知,com.mysql.jdbc.Connection的構造函數public java.sql.Connection connect(String url, Properties info)會在構造的時候接受一個Properties型的參數,其中的“useUnicode”和“characterEncoding”決定了它是否在客戶端和服務器端傳輸過程中進行Encode,以及如何進行Encode。詳細可參見private void checkServerEncoding()方法。
Hibernate使用net.sf.hibernate.cfg.Environment來存儲系統級的所有屬性,而用net.sf.hibernate.cfg.Settings來存儲Hibernate的設定。
但是net.sf.hibernate.cfg.Environment里保存的Properties不是直接提供給com.mysql.jdbc.Connection使用的。
net.sf.hibernate.connection.ConnectionProviderFactory會在public void configure(Properties props)中使用用public static Properties getConnectionProperties(Properties properties)方法進行篩選。
帶有特定前綴public static final String CONNECTION_PREFIX = "hibernate.connection"并且沒有被放到private static final Set SPECIAL_PROPERTIES里的屬性才會被留下來。
然后,它在public Connection getConnection()中建立連接的時候使用的是它自己篩選完之后的private Properties connectionProps屬性。
所以答案就很明顯了。
使用hibernate.cfg.xml的話,在<session-factory>和</session-factory>之間加入這么一段:
如果是些程序的話,在創建完net.sf.hibernate.cfg.Configuration、并使用configure()讀取完配置文件之后,buildSessionFactory()之前,執行如下代碼:
OK!萬事大吉了!
*直接寫在connection url后面也可以
Hibernate配置文件使用xml格式嗎?試試看把connection url后面的 & 符號用xml轉義符替代試試看,或者用<![CDATA[]]>也行。
Hibernate使用net.sf.hibernate.cfg.Environment來存儲系統級的所有屬性,而用net.sf.hibernate.cfg.Settings來存儲Hibernate的設定。
但是net.sf.hibernate.cfg.Environment里保存的Properties不是直接提供給com.mysql.jdbc.Connection使用的。
net.sf.hibernate.connection.ConnectionProviderFactory會在public void configure(Properties props)中使用用public static Properties getConnectionProperties(Properties properties)方法進行篩選。
帶有特定前綴public static final String CONNECTION_PREFIX = "hibernate.connection"并且沒有被放到private static final Set SPECIAL_PROPERTIES里的屬性才會被留下來。
然后,它在public Connection getConnection()中建立連接的時候使用的是它自己篩選完之后的private Properties connectionProps屬性。
所以答案就很明顯了。
使用hibernate.cfg.xml的話,在<session-factory>和</session-factory>之間加入這么一段:
java代碼: |
<property name="connection.useUnicode">true</property> <property name="connection.characterEncoding">UTF-8</property> |
如果是些程序的話,在創建完net.sf.hibernate.cfg.Configuration、并使用configure()讀取完配置文件之后,buildSessionFactory()之前,執行如下代碼:
java代碼: |
Properties extraProperties = new Properties(); extraProperties.put("hibernate.connection.useUnicode", "true"); extraProperties.put("hibernate.connection.characterEncoding", "UTF-8"); myConfiguration.addProperties(extraProperties); |
*直接寫在connection url后面也可以
Hibernate配置文件使用xml格式嗎?試試看把connection url后面的 & 符號用xml轉義符替代試試看,或者用<![CDATA[]]>也行。