Tom O'Brien Tom O'Brien - 5 months ago 37
Java Question

MysqlDataSource throwing ClassCastException in Glassfish

I am trying to create a

MysqlDataSource
object to connect to my database. I need to do this so I can use the
setRewriteBatchedStatements(boolean)
method.

MysqlDataSource mysql mysql = (MysqlDataSource) context.lookup("jdbc/MySQLDataSource");


It throws the following exception:

2015-07-15T14:25:46.078+0100|Severe: java.lang.ClassCastException: com.sun.gjc.spi.jdbc40.DataSource40 cannot be cast to com.mysql.jdbc.jdbc2.optional.MysqlDataSource
at com.pododdle.dao.MySQL.mysql_conn(MySQL.java:30)
at com.pododdle.dao.MySQL.getMySQLConnection(MySQL.java:48)
at com.pododdle.dao.PodcastService.getPodcasts(PodcastService.java:112)
at com.pododdle.resources.FeedResource.getNewEpisodes(FeedResource.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)


Previously I was using a
DataSource
object, and everything worked superbly, but I need to set the above property and the
DataSource
object doesn't do this. The previous code read:

mysql = (DataSource) context.lookup("jdbc/MySQLDataSource");


I am running the code on the Glassfish 4 webserver, and connecting to a MySQL5.6 datbase.

Answer

This classcastexception was avoided by doing the following steps:

DataSource datasource = (DataSource) context.lookup("jdbc/MySQLDataSource");
MysqlDataSource mysql_datasource = datasource.unwrap(MysqlDataSource.class);

You can now set the rewriteBatchedStatements to true with no problems!

mysql_datasource.setRewriteBatchedStatements(true);
Connection conn = mysql.getConnection();