Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the jdbc ClientInfo in a MySQL DataSource

Tags:

java

mysql

jdbc

In Java with MySQL we want to add the jdbc ClientInfo to identify the source of each query. Currently we can do something like:

    try(Connection connection = dataSource.getConnection()){
        connection.setClientInfo("ApplicationName", "MyApp");
    }

But I need to add it to every connection created and means checking all the source code for places where a new connection is created. I will like to set it to the DataSource level.

So far what works for me is to extends the DataSource with a custom overriden getConnection method that calls setClientInfo. This is not only a dirty workarround but datasource specific.

I have seen that mysql driver has ClientInfoProviders like the default com.mysql.cj.jdbc.CommentClientInfoProvider. A custom ClientInfoProvider can be configured like:

    Properties properties = new Properties();
    properties.setProperty(PropertyKey.clientInfoProvider.getKeyName(), "foo.bar.CustomClientInfoProvider");
    properties.setProperty(APPLICATION_NAME, "MyApp");

    HikariConfig dataSourceConfig = new HikariConfig();
    dataSourceConfig.setDataSourceProperties(properties);
    ...

But it is only called if someone calls the getClientInfo in the connection anyway.

So I will like to know:

  • Is there support in the MySql driver to set the clientInfo in the DataSource just by setting properties?
  • If there is a way. How can it be done?
like image 442
borjab Avatar asked Sep 17 '25 13:09

borjab


1 Answers

I think you can use AspectJ as a possible solution for it. You can create an aspect which will intercept calls of the DataSource.getConnection method and then call the setClientInfo method with configured parameters when the connection is established.

like image 195
Ilya Lysenko Avatar answered Sep 20 '25 04:09

Ilya Lysenko