hibernate.cfg.xml加上属性.
<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">UTF-8</property>
mysql 的驱动用3.0.15以上版本的,
加个Filter, 使用UTF-8字符集就可以了,
例如:在hibernate.cfg.xml文件中,如下 :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!--
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:SXT</property>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
-->
<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">UTF-8</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup
<property name="hbm2ddl.auto">update</property>-->
<mapping class="com.nong.hibernate.model.Teacher"/>
</session-factory>
</hibernate-configuration>
若使用Spring 在spring的配置文件 applicationContex.xml里不知道怎么写,怎么试都不行,后来在web.xml里面配置,就可以了。
在web.xml 里面配置过滤器
<!--encodingFilter -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class> org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
以下参考:
1.我的数据库中的表的字符集是gbk
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=gbk
2.连接数据库的字符串 (配合spring写法)
url=jdbc\:mysql\://localhost\:3306/test?useUnicode\=true&characterEncoding\=GBK
在jdbc.properties 文件里面
jdbc.url=jdbc:mysql://localhost:3306/lss?useUnicode=true&characterEncoding=GBK
3.果如两者不同意 中文数据就不能入库 回报一个错误
java.sql.SQLException: Incorrect string value: '\xC3\xA5\