日期:2014-05-16  浏览次数:20401 次

hibernate连接数据库乱码

在开发中,已经确定数据库的编码格式设置为UTF8,同时导入的sql也是UTF8,但在用eclipse进行开发的时候,发现读出的数据依旧乱码,这时候怀疑是hibernate的编码问题。

?

更改hibernate的配置如下;

<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName">
			<value>com.mysql.jdbc.Driver</value>
		</property>
		<property name="url">
			<value>jdbc:mysql://127.0.0.1:3306/db?characterEncoding=UTF-8</value>
		</property>
		<property name="username">
			<value>root</value>
		</property>
		<property name="password">
			<value>123456</value>
		</property>
	</bean>

?同时修改hibernate的属性

<property name="hibernateProperties">
			<props>
				<!--此处用来定义hibernate的SessionFactory的属性:不同数据库连接,启动时选择create,update,create-drop -->
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.c3p0.min_size">5</prop>
				<prop key="hibernate.c3p0.max_size">20</prop>
				<prop key="hibernate.c3p0.timeout">300</prop>
				<prop key="hibernate.c3p0.max_statements">50</prop>
				<prop key="hibernate.c3p0.idle_test_period">3000</prop>
				<prop key="connection.characterEncoding">UTF-8</prop> 
				<prop key="connection.useUnicode">true</prop> 
				<!-- Show and print nice SQL on stdout -->
				<prop key="show_sql">true</prop>
				<prop key="format_sql">true</prop>
			</props>
</property>

?