My system runs on Linux Mandriva, RDBMS - MySQL 5. I need to have the database and tables created in UTF-8.
Here i
Via Spring Java Config dataSource() this should help:
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
//your username/pass props
dataSource.setConnectionProperties("useUnicode=true;characterEncoding=utf8;characterSetResults=UTF-8;");
return dataSource;
}
Be careful about ';' at the end of properties string!
I'm using Spring-Data. I've tried activating parameters in the URL:
jdbc:mysql://localhost:3306/DATABASE?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf-8
Also, I've tried with hibernate properties, but the solution which definitively worked for me is the one proposed by @Gray
@Bean
@Autowired
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(dbGenerateDdl);
vendorAdapter.setShowSql(dbShowSql);
if (Arrays.asList(environment.getActiveProfiles()).contains("prod"))
vendorAdapter.setDatabasePlatform(CustomMysqlDialect.class.getName());
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.connection.CharSet", "utf-8");
jpaProperties.put("hibernate.connection.useUnicode", true);
jpaProperties.put("hibernate.connection.characterEncoding", "utf-8");
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.example.model");
factory.setDataSource(dataSource);
factory.setJpaProperties(jpaProperties);
return factory;
}
This line saved my day:
vendorAdapter.setDatabasePlatform(CustomMysqlDialect.class.getName());
You can also create databases with encoding.
Simply use phpMyAdmin for the database/table creation.
There are some URL parameters you would specify in the URL of the hibernate settings to have the connection using UTF8:
<!-- Database Settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- for performance reasons changed to MyISAM from org.hibernate.dialect.MySQLInnoDBDialect -->
<property name="dialect">org.openmeetings.app.hibernate.utils.MySQL5MyISAMDialect</property>
<property name="connection.url">jdbc:mysql://localhost/openmeetings?autoReconnect=true&useUnicode=true&createDatabaseIfNotExist=true&characterEncoding=utf-8</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
You don't need to set the whole encoding in the database to utf8 Only if you are using
<!-- Database Scheme Auto Update -->
<property name="hbm2ddl.auto">update</property>
You WILL have to set the default encoding of MySQL to utf8. Cause the hbm2dll will use the default encoding of the database.
You might still use hbm2ddl.auto, and modify the table's of the database manually to have utf8 collation.
If you are not using hbm2ddl.auto, you can simply create the tables with your favorite encoding.
No need to set the database to a special encoding.
Sebastian
You can Use Hibernate @Type attribute,Based on your requirement you can customize the annotation and apply on top of the fied. like :
public class PhoneNumberType implements UserType {
@Override
public int[] sqlTypes() {
return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER};
}
@Override
public Class returnedClass() {
return PhoneNumber.class;
}
// other methods
}
First, the null SafeGet method:
@Override
public Object nullSafeGet(ResultSet rs, String[] names,
SharedSessionContractImplementor session, Object owner) throws HibernateException,
SQLException {
int countryCode = rs.getInt(names[0]);
if (rs.wasNull())
return null;
int cityCode = rs.getInt(names[1]);
int number = rs.getInt(names[2]);
PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number);
return employeeNumber;
}
Next, the null SafeSet method:
@Override
public void nullSafeSet(PreparedStatement st, Object value,
int index, SharedSessionContractImplementor session)
throws HibernateException, SQLException {
if (Objects.isNull(value)) {
st.setNull(index, Types.INTEGER);
} else {
PhoneNumber employeeNumber = (PhoneNumber) value;
st.setInt(index,employeeNumber.getCountryCode());
st.setInt(index+1,employeeNumber.getCityCode());
st.setInt(index+2,employeeNumber.getNumber());
}
}
Finally, we can declare our custom PhoneNumberType in our OfficeEmployee entity class:
@Entity
@Table(name = "OfficeEmployee")
public class OfficeEmployee {
@Columns(columns = { @Column(name = "country_code"),
@Column(name = "city_code"), @Column(name = "number") })
@Type(type = "com.baeldung.hibernate.customtypes.PhoneNumberType")
private PhoneNumber employeeNumber;
// other fields and methods
}
This might solve your problem, This will work for all database. if you want more info refer :: https://www.baeldung.com/hibernate-custom-types similarly you have to do UTF-8 encoding/Decoding and ISO-8859-1 Decoding/encoding
For those who use Spring Boot: add the characterEncoding=utf8 parameter to your application.properties file to this line:
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
Consider changing the connection url configuration like this:
<property name="hibernate.connection.url">
jdbc:mysql://localhost/yourdatabase?UseUnicode=true&characterEncoding=utf8
</property>
It solves the case.