JDBC “java.io.NotSerializableException” occurs while using Spring JDBC Template for connectivity and passing arguments for searching/update as parameters. Because JDBC parameters always required searialize objects.
Mostly happen when forget to use get fields value from object and class is not serializable.
Example :
Exception Message
Invalid argument value: java.io.NotSerializableException; nested exception is java.sql.SQLException: Invalid argument value: java.io.NotSerializableException
Class using
public class DynamicDashboard { private int dashboardId; private String dashboardName; private String htmlContent; private String scriptContent; private String ruleContent; public DynamicDashboard() { super(); } //Getter and Setters
Below is my DAO class method where this exception occured for column RULE_CONTENT.
public void addDashboard(DynamicDashboard dynamicDashboard) { String sql = "INSERT INTO dynamic_dashboard " + "(DASHBOARD_NAME, HTML_CONTENT,SCRIPT_CONTENT,RULE_CONTENT) VALUES (?, ?, ?,?)"; try { jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql, new Object[] { dynamicDashboard.getDashboardName(), dynamicDashboard.getHtmlContent(), dynamicDashboard.getScriptContent(), dynamicDashboard}); } catch (Exception ex) { logger.error(ex.getMessage()); } }
In above method we forget to get last parameter value for rule like dynamicDashboard.getRuleContent()for database column RULE_CONTENT because JDBCTemplate always required serializable object and all wrapper classes(Integer, String etc.) are searializable. It will through exception “java.io.NotSerializableException” as above.
Solution :
Add get method for ruleContent for object dynamicDashboard.
Correct Code
public void addDashboard(DynamicDashboard dynamicDashboard) { String sql = "INSERT INTO dynamic_dashboard " + "(DASHBOARD_NAME, HTML_CONTENT,SCRIPT_CONTENT,RULE_CONTENT) VALUES (?, ?, ?,?)"; try { jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql, new Object[] { dynamicDashboard.getDashboardName(), dynamicDashboard.getHtmlContent(), dynamicDashboard.getScriptContent(), dynamicDashboard.getRuleContent()}); } catch (Exception ex) { logger.error(ex.getMessage()); } }
More Issues
For more JDBC issue solution follow link Common JDBC Issues.
Leave you feedback to enhance more on this topic so that make it more helpful for others.