我现在有问题。我正在通过Azure使用Clear db。我无法将UTF8字符存储到表中。我正在使用Spring + Hibernate + Mysql组合。
我可以通过更新my.cnf
文件来使其在本地工作,但是在Azure上它不允许我更新,因为我正在使用社区版并且被许多用户使用。他们建议遵循以下几点。但是我不知道如何在休眠配置中设置它
每次打开数据库连接时,在执行任何查询或要在该连接上运行的查询之前,应使用https://dev.mysql.com/doc/refman/5.5/en/set-names.html中说明的语法发出SET NAMES查询。因此,例如,设置所需的字符集和排序规则,可以使用
SET NAMES utf8 COLLATE utf8_bin;
下面给出了我的休眠文件
@Configuration
@EnableTransactionManagement
public class HibernateConfig {
/**
* Uses an datasource library for local testing with out creating datasources on the server. Not to be used for Production.
*
* @return
*/
@Bean
public DriverManagerDataSource jndiDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://<azureurl>-f.cloudapp.net:3306/db1");
dataSource.setUsername("user");
dataSource.setPassword("pw");
return dataSource;
}
/**
* Datasource to be used when running on App servers
* @return
* @throws javax.naming.NamingException
*/
/*public @Bean
DataSource jndiDataSource() throws NamingException{
return (DataSource) new InitialContext().lookup(environment.getProperty("datasourceJndi"));
}
*/
/**
* @return
* @throws javax.naming.NamingException
*/
@Bean
public org.springframework.orm.hibernate4.LocalSessionFactoryBean sessionFactory() throws NamingException {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
Properties prop = new Properties();
prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
//prop.put("hibernate.dialect", "org.hibernate.dialect.OracleDialect");
//Be extremely careful before changing this value to Update or Create
prop.put("hibernate.hbm2ddl.auto", "none");
prop.put("hibernate.show_sql", "false");
prop.put("hibernate.enable_lazy_load_no_trans","true");
prop.put("hibernate.connection.CharSet","utf8");
prop.put("hibernate.connection.characterEncoding","utf8");
prop.put("hibernate.connection.useUnicode",true);
sessionFactory.setDataSource(this.jndiDataSource());
sessionFactory.setPackagesToScan(new String[]{"com.sp.domain"});
sessionFactory.setHibernateProperties(prop);
return sessionFactory;
}
/**
* @return
* @throws javax.naming.NamingException
*/
@Bean
public HibernateTransactionManager transactionManager() throws NamingException {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setDataSource(this.jndiDataSource());
txManager.setSessionFactory(this.sessionFactory().getObject());
return txManager;
}
}