Depending on the particular ClearDB database server, there will be cases when your database's characters set is latin1 (the default configuration for MySQL older than 8.1).
We have contacted the ClearDB support team, but they were not willing to change this configuration because it could affect other customers hosted on the same server and they offered us a more expensive solution: to have our own dedicated servers.
The good point is that the character set can be configured per connection bases, so we decided to override the default DataSource, autoconfigured by the Java buildpack used by the Cloud Foundry.
In order to override the DataSource, we needed to do several things:
- Add Maven dependency for Spring Cloud connectors,
- Turn-off the default autoconfiguration of the DataSource bean,
- Configure the DataSource bean by using connection parameters provided by the environment.
To add Spring Cloud connectors, add this dependency to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cloud-connectors</artifactId>
</dependency>
In order to turn off the auto-configuration, be sure to create Cloud bean in spring-boot cloud profile:
@Configuration
@Profile("cloud")
public class DataSourceConfiguration {
@Bean
public Cloud cloud() {
return new CloudFactory().getCloud();
}
}
Finally, to use database connection parameters hosted within VCAP_SERVICES environment variables, you can reference them in the application-cloud.yml in this way:
spring.datasource.url: ${cloud.services.mysql.connection.jdbcurl}&characterEncoding=utf-8
spring.datasource.username: ${cloud.services.mysql.connection.username}
spring.datasource.password: ${cloud.services.mysql.connection.password}
spring.datasource.testOnBorrow: true
When it comes to customizing DataSource configuration, it is important to pay attention to spring.datasource.url that ends with characterEncoding=utf-8: this is where connections are configured to use the UTF-8 encoding.
Also, mysql is the name of the PCF service instance in our case and can be different in your environment.
Finally, to learn more about binding to data services with Spring Boot, you can read this excellent article: https://spring.io/blog/2015/04/27/binding-to-data-services-with-spring-boot-in-cloud-foundry.