简体   繁体   English

Hibernate SessionFactory创建新连接后,如何立即运行SQL查询?

[英]How to run an SQL query right after Hibernate SessionFactory creates a new connection?

My server uses Hibernate in order to connect to a MySQL db. 我的服务器使用Hibernate来连接到MySQL数据库。 I'm also using c3p0 for connection pooling. 我还将c3p0用于连接池。 I want to execute a specific sql query once on each connection when it is created, but since I'm using ComboPooledDataSource , there is no way to detect when a new session is created. 我想在创建每个连接时对每个连接执行一次特定的sql查询,但是由于我使用的是ComboPooledDataSource ,因此无法检测何时创建新会话。 I found out that I can run my query by enabling test connection on checkout and set the query that I want to run as preferred test query (but it can run more than once). 我发现我可以通过在结帐时启用测试连接来运行我的查询,并将要运行的查询设置为首选测试查询(但是它可以运行多次)。

String query = "my query";
comboPooledDataSource.setTestConnectionOnCheckout(true);
comboPooledDataSource.setPreferredTestQuery(query);

Is there a more elegant way to accomplish this? 有没有更优雅的方法可以做到这一点?

* Edit * *编辑*

I'm trying to make my db accept utf8mb4 characters. 我试图使我的数据库接受utf8mb4字符。 The acceptable way to do it is by applying the following to the my.cnf file: 可接受的方法是将以下内容应用于my.cnf文件:

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

The problem is that I don't have access to anything but my db, so my solution is to execute SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci; 问题是我除数据库外无权访问其他内容,因此我的解决方案是执行SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci; for each connection. 对于每个连接。

See c3p0's ConnectionCustomizer interface. 请参阅c3p0的ConnectionCustomizer界面。 Override the onAcquire(...) method of AbstractConnectionCustomizer . 重写AbstractConnectionCustomizeronAcquire(...)方法。 onAcquire(...) is called just once for each Connection, after it has been acquired from the database, before it is made available for check-out by clients. 从数据库中获取onAcquire(...)后,每个Connection仅被调用一次,之后才可供客户端检出。

Or, if you want you can just use c3p0's built-in example for just this sort of use case, com.mchange.v2.c3p0.example.InitSqlConnectionCustomizer 或者,如果您愿意,可以仅将c3p0的内置示例用于这种用例,即com.mchange.v2.c3p0.example.InitSqlConnectionCustomizer

In c3p0.properties: 在c3p0.properties中:

c3p0.connectionCustomizerClassName=com.mchange.v2.c3p0.example.InitSqlConnectionCustomizer
c3p0.extensions.initSql=SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM