Tom O'Brien Tom O'Brien - 6 months ago 54
Java Question

MysqlDataSource throwing ClassCastException in Glassfish

I am trying to create a

object to connect to my database. I need to do this so I can use the

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(
at com.pododdle.dao.MySQL.getMySQLConnection(
at com.pododdle.dao.PodcastService.getPodcasts(
at com.pododdle.resources.FeedResource.getNewEpisodes(
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(
at sun.reflect.DelegatingMethodAccessorImpl.invoke(
at java.lang.reflect.Method.invoke(

Previously I was using a
object, and everything worked superbly, but I need to set the above property and the
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.


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!

Connection conn = mysql.getConnection();