I’m using JDBC Connection pooling with mysql.
This is my code
private static DataSource _ds;
/**
* create the data source if it doesn't exist
*/
private DataSource getDataSource() throws FileNotFoundException,
IOException, URISyntaxException
{
if (_ds != null)
return _ds;
PoolProperties p = new PoolProperties();
p.setUrl(url);
p.setDriverClassName(driver);
p.setUsername(username);
p.setTestOnBorrow(true);
if (password != null)
{
p.setPassword(password);
}
p.setValidationQuery(validationQuery);
p.setJdbcInterceptors(JDBC_INTERCEPTOR);
DataSource datasource = new DataSource();
datasource.setPoolProperties(p);
_ds = datasource;
return datasource;
}
/**
* gets a connection from the JDBC pool
*
* @throws SQLException
* @throws IOException
* @throws FileNotFoundException
* @throws URISyntaxException
*/
public Connection getConnection() throws SQLException,
FileNotFoundException, IOException, URISyntaxException
{
Connection con = getDataSource().getConnection();
con.setAutoCommit(false);
return con;
}
And whenever i want to use a connection I do :
con = getInstance().getConnection();
stmt = con.createStatement();
resultSet = stmt.executeQuery(selectQuery);
The problem is that the results of the query are not realtime. That is if I change something in the DB and commit, the query in java doesn’t get the changes.same happens if the DB is changed from another app
Note : the changes are taken after a while, or if i restart tomcat
Is there anything wrong with my code? anyway to fix this error?
Thank you
Most probably this is caused by MySQL’s default isolation level which is REPEATABLE READ.
This means that you don’t see changes done by other transactions until you end (commit, rollback) your “own” transaction (remember: a SELECT already starts a transaction)
As the connections in a pool are never closed, those transactions are probably not ended. Try issuing a commit or rollback before running the select.
For a permanent solution you can either change the default isolation by configuring your connection pool (most of them allow this), change the transaction level by calling
setTransactionIsolation()on the connection or by changing the default level in MySQL.