Hibernate in JSF Social Application runs out of connections - mysql

I'm currently writing a JSF based Social Application. I'm also using Hibernate to persist, update and merge data. But at some point my application stops responding with following error.
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections"
at sun.reflect.GeneratedConstructorAccessor848.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1114)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2502)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2535)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2320)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.GeneratedConstructorAccessor822.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:347)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
... 127 more
the java code that executes transactions is here:
public class TransactionManager {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public TransactionManager() {
}
public IEntity validateUser(String userName, String userPassword) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
String hql = "FROM AccountEntity";
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<IAccountEntity> results = query.list();
for (IAccountEntity user : results) {
if (user.getUserName().equals(userName) && user.getPassword().equals(userPassword)) {
session.close();
sessionFactory.close();
return user;
}
}
session.close();
sessionFactory.close();
return null;
}
public IEntity retrieveUserByName(String userName) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
String hql = "FROM AccountEntity A WHERE A.userName = '" + userName + "'";
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<IAccountEntity> results = query.list();
session.close();
sessionFactory.close();
if (!results.isEmpty()) {
return results.get(0);
}
return null;
}
public IEntity retrievePageByName(String pageName) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
String hql = "FROM PageEntity A WHERE A.pageName = '" + pageName + "'";
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<IAccountEntity> results = query.list();
session.close();
sessionFactory.close();
if (!results.isEmpty()) {
return results.get(0);
}
return null;
}
public Map<IEntity, Integer> save(Object... objects) {
Map<IEntity, Integer> savedMap = new HashMap<IEntity, Integer>();
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
for (Object object : objects) {
session.save(object);
savedMap.put((IEntity) object, ((IEntity) object).getId());
}
session.getTransaction().commit();
session.close();
sessionFactory.close();
return savedMap;
}
public void merge(IEntity entity) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.update(entity);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
// SELECT * FROM `commententity` WHERE id BETWEEN 3 and 5 and
// accountEntityId = 1 ORDER BY id DESC
// SELECT * FROM `commententity` WHERE targetAccountEntity_id='1' ORDER BY
// id LIMIT 5 OFFSET 0
// FROM dao.CommentEntity D WHERE targetAccountEntity_id='1' ORDER BY D.id
// DESC
public List<IEntity> retrievePaginatedById(String classType, String targetId, String status, int id, int offset,
int limit, boolean forContactRequestNotification) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
String hql = null;
if (forContactRequestNotification) {
hql = "FROM " + classType + " D WHERE " + targetId + "=" + "'" + id + "' AND D.status = '" + status
+ "' ORDER BY D.id DESC";
} else {
hql = "FROM " + classType + " D WHERE " + targetId + "=" + "'" + id + "'" + " ORDER BY D.id DESC";
}
Query query = session.createQuery(hql).setFirstResult(offset).setMaxResults(limit);
#SuppressWarnings("unchecked")
List<IEntity> results = query.list();
session.close();
sessionFactory.close();
return results;
}
public List<IEntity> retrieveMultipleById(String classType, String targetId, String status, int id,
boolean forContactRequestNotification) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
String hql = null;
if (forContactRequestNotification) {
// SONDERFALL
hql = "FROM " + classType + " D WHERE D.status = '" + status + "' and " + targetId + "= " + id;
} else {
hql = "FROM " + classType + " D WHERE " + targetId + "= " + id;
}
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<IEntity> results = query.list();
session.close();
sessionFactory.close();
return results;
}
public IEntity retrieveById(Class<?> c, int id) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
IEntity entity = (IEntity) session.get(c, id);
session.close();
sessionFactory.close();
return entity;
}
public void delete(IEntity obj) {
SessionFactory sessionFactory = createSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.delete(obj);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
public static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
and this is a sample image of how a profile looks like, I'm supporting lazy loading to avoid big transactions.
I just dont get what am I doing so wrong here. I read somewhere I have to close every connection. But that doesn't seem to solve the problem.

Please increase the mysql connection size.
Go to mysql console and run below
SHOW VARIABLES LIKE "max_connections";
You will see the maximum allowed connections. You can change them using
SET GLOBAL max_connections = 200;
Restart mysql server, and it should be working fine.

Related

SQL conflict with mysql(MariaDB) in Gaia Environment

I am a bit confused with my situation as i am new to Gaia environment.
The situation is,
I have 2 databases one is Oracle(External Database) and another is Mysql in Mariadb platform. The ultimate goal is to transfer the data from Oracle to MariaDB through Springboot application.
I have a Issue now, I am able to get through Connections through GaiaConfig file,
package com.jpmc.pulsar.config;
#Configuration
#Profile({"gaia"})
public class GaiaConfig {
#Autowired
private Environment env;
private static final Logger LOG = LoggerFactory.getLogger(GaiaConfig.class);
#Autowired
private DataSource oracleDataSource;
#Autowired
private DataSource mysqlDataSource;
#Bean
public Cloud cloud() {
return new CloudFactory().getCloud();
}
#Bean(name = "oracleDb")
public DataSource oracleDataSource(final Cloud cloud) {
return createDataSource("external-database", cloud);
}
#Bean(name = "oracleJdbcTemplate")
public JdbcTemplate oracleJdbcTemplate() {
return new JdbcTemplate(oracleDataSource);
}
private DataSource createDataSource(final String serviceName, final Cloud cloud) {
final ExternalDependency externalDependency = cloud
.getServiceConnector(serviceName, ExternalDependency.class, null);
if (externalDependency == null) {
throw new InvalidConfigurationException(
String.format("Error getting ServiceConnector for External Dependency with serviceName=[%s]", serviceName)
);
}
HikariDataSource dataSource = null;
try {
final HikariConfig config = new HikariConfig();
config.setDriverClassName(requiredStringProperty("driverClassName", externalDependency, serviceName));
config.setJdbcUrl(requiredStringProperty("jdbcUrl", externalDependency, serviceName));
config.setUsername(requiredStringProperty("username", externalDependency, serviceName));
config.setPassword(requiredStringProperty("password", externalDependency, serviceName));
config.setConnectionTestQuery(requiredStringProperty("connectionTestQuery", externalDependency, serviceName));
config.setMinimumIdle(intProperty("minimumIdle", externalDependency, serviceName, 1));
config.setMaximumPoolSize(intProperty("maximumPoolSize", externalDependency, serviceName, 5));
dataSource = new HikariDataSource(config);
String dataSourceDetails = dataSourceDetails(dataSource);
LOG.info("Available DataSource: [{}]", dataSourceDetails);
} catch (Exception e) {
LOG.info("{}", e);
}
return dataSource;
}
private String dataSourceDetails(final HikariDataSource dataSource) {
final StringBuilder sb = new StringBuilder();
sb.append("driverClassName=[").append(dataSource.getDriverClassName()).append("],");
sb.append("jdbcUrl=[").append(dataSource.getJdbcUrl()).append("],");
sb.append("username=[").append(dataSource.getUsername()).append("],");
sb.append("connectionTestQuery=[").append(dataSource.getConnectionTestQuery()).append("],");
sb.append("validationTimeout=[").append(dataSource.getValidationTimeout()).append("],");
sb.append("maximumPoolSize=[").append(dataSource.getMaximumPoolSize()).append("],");
sb.append("minimumIdle=[").append(dataSource.getMinimumIdle()).append("],");
sb.append("connectionTimeout=[").append(dataSource.getConnectionTimeout()).append("],");
sb.append("connectionInitSql=[").append(dataSource.getConnectionInitSql()).append("],");
sb.append("maxLifetime=[").append(dataSource.getMaxLifetime()).append("]");
return sb.toString();
}
private Boolean booleanProperty(final String propertyName, final ExternalDependency externalDependency) {
final String value = externalDependency.getCredential(propertyName);
if (value != null) {
return Boolean.parseBoolean(value);
}
return Boolean.FALSE;
}
private Integer intProperty(final String propertyName, final ExternalDependency externalDependency,
String serviceName, final int defaultValue) {
final String value = externalDependency.getCredential(propertyName);
if (value != null) {
try {
return Integer.valueOf(value);
} catch (NumberFormatException ex) {
throw new InvalidConfigurationException(
String.format("Property [%s] is not a valid int in External Dependency with serviceId=[%s]",
propertyName, serviceName), ex);
}
}
return defaultValue;
}
private String requiredStringProperty(final String propertyName, final ExternalDependency externalDependency,
String serviceName) {
final String value = stringProperty(propertyName, externalDependency);
if (value == null || value.trim().length() == 0) {
throw new InvalidConfigurationException(
String.format("No property [%s] defined as part of External Dependency with serviceId=[%s]",
propertyName, serviceName));
} else {
return value;
}
}
private String stringProperty(final String propertyName, final ExternalDependency externalDependency) {
return externalDependency.getCredential(propertyName);
}
//MySQL Bean and jdbcTemplate Working Fine
#Primary
#Bean(name = "mysqlDb")
public DataSource mysqlDataSource(final Cloud cloud) {
final String serviceId = "bsc-mariadb";
// https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html
final Properties mysqlProperties = new Properties();
mysqlProperties.setProperty("cachePrepStmts", "true");
mysqlProperties.setProperty("prepStmtCacheSize", "250");
mysqlProperties.setProperty("prepStmtCacheSqlLimit", "2048");
mysqlProperties.setProperty("useServerPrepStmts", "true");
mysqlProperties.setProperty("useLegacyDatetimeCode", "false");
mysqlProperties.setProperty("serverTimezone", "UTC");
mysqlProperties.setProperty("connectionCollation", "utf8mb4_unicode_ci");
// https://github.com/brettwooldridge/HikariCP#configuration-knobs-baby
final Map<String, Object> poolProperties = new HashMap<>();
poolProperties.put("poolName", serviceId + "-pool");
poolProperties.put("maximumPoolSize", 10);
poolProperties.put("maxLifetime", Duration.ofMinutes(5).toMillis());
poolProperties.put("connectionInitSql", "SET character_set_client = utf8mb4;");
poolProperties.put("dataSourceProperties", mysqlProperties);
final DataSourceConfig serviceConfig = new DataSourceConfig(poolProperties);
final DataSource dataSource = cloud.getServiceConnector(serviceId, DataSource.class, serviceConfig);
LOG.info("Available DataSource: [{}]", dataSource);
return dataSource;
}
#Bean(name = "mysqlJdbcTemplate")
public JdbcTemplate jdbcTemplate(#Qualifier("mysqlDb") DataSource dsMySQL) {
return new JdbcTemplate(dsMySQL);
}
}
and My Repository class looks like this,
#Autowired
private JdbcTemplate mysqlJdbcTemplate;
#Autowired
private JdbcTemplate oracleJdbcTemplate;
private String tableName = "BSC_INCIDENT_STG";
private String sql = "INSERT INTO `BSC_INCIDENT_STG`(`INCIDENT_NUMBER`,`APPLICATION_ID`,`CATEGORY`,`OPEN_TIME`,`SEVERITY_CODE`,`ASSIGNMENT`,`STATUS`,`CLOSE_TIME`,`ELAPSED_TIME`,`RESOLUTION_CODE`,`TYPE`,`OPEN_GROUP`,`RESOLVED_GROUP`,`RESOLVED_TIME`,`USER_PRIORITY`,`JP_ACCT_LOB`,`JP_ACCT_APP_RTO`,`JP_IMPACT`,`JP_IMPACT_DURATION_MIN`,`JP_OUTAGE_DURATION_MIN`,`JP_TTR_D1`,`JP_TTR_D2`,`JP_TTR_R1`,`JP_TTR_R2`,`JP_TTR_D2R2`,`LOGICAL_NAME`,`JP_EXTERNAL_ID`,`JP_EXTERNAL_SYSTEM`,`JP_CONFIG_ITEM`,`JP_MASTER_HOST`,`JP_SITE`,`JP_APPSERVICE_NAME`,`JP_APPSERVICE_ID`,`JP_VERUMIDENTIFIER`)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
public boolean truncateAndLoad(final List<Incident> incidentList) {
mysqlJdbcTemplate.execute("TRUNCATE BSC_INCIDENT_STG");
mysqlJdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1, incidentList.get(i).getIncidentNumber());
ps.setString(2, incidentList.get(i).getApplicationId());
ps.setString(3, incidentList.get(i).getCategory());
ps.setString(4, incidentList.get(i).getOpenTime());
ps.setString(5, incidentList.get(i).getSeverityCode());
ps.setString(6, incidentList.get(i).getAssignment());
ps.setString(7, incidentList.get(i).getStatus());
ps.setString(8, incidentList.get(i).getCloseTime());
ps.setString(9, incidentList.get(i).getElapsedTime());
ps.setString(10, incidentList.get(i).getResolutionCode());
ps.setString(11, incidentList.get(i).getType());
ps.setString(12, incidentList.get(i).getOpenGroup());
ps.setString(13, incidentList.get(i).getResolvedGroup());
ps.setString(14, incidentList.get(i).getResolvedTime());
ps.setString(15, incidentList.get(i).getUserPriority());
ps.setString(16, incidentList.get(i).getJpAcctLob());
ps.setString(17, incidentList.get(i).getJpAcctAppRto());
ps.setString(18, incidentList.get(i).getJpImpact());
ps.setString(19, incidentList.get(i).getJpImpactDurationMin());
ps.setString(20, incidentList.get(i).getJpOutageDurationMin());
ps.setString(21, incidentList.get(i).getJpTtrD1());
ps.setString(22, incidentList.get(i).getJpTtrD2());
ps.setString(23, incidentList.get(i).getJpTtrR1());
ps.setString(24, incidentList.get(i).getJpTtrR2());
ps.setString(25, incidentList.get(i).getJpTtrD2R2());
ps.setString(26, incidentList.get(i).getLogicalName());
ps.setString(27, incidentList.get(i).getJpExternalId());
ps.setString(28, incidentList.get(i).getJpExternalSystem());
ps.setString(29, incidentList.get(i).getJpConfigItem());
ps.setString(30, incidentList.get(i).getJpMasterHost());
ps.setString(31, incidentList.get(i).getJpSite());
ps.setString(32, incidentList.get(i).getJpAppserviceName());
ps.setString(33, incidentList.get(i).getJpAppserviceId());
ps.setString(34, incidentList.get(i).getJpVerumidentifier());
}
#Override
public int getBatchSize() {
return incidentList.size();
}
});
return true;
}
public String getTableName() {
return tableName;
}
public List<Incident> listAll() {
String cprSql = "SELECT a.NUMBERPRGN as INCIDENT_NUMBER,"
+ "a.JP_ACCT_APP_APPID as APPLICATION_ID,"
+ "a.CATEGORY,"
+ "to_char(a.OPEN_TIME_EST,'DD-MON-YYYY hh24:mi:ss') OPEN_TIME,"
+ "a.SEVERITY_CODE,"
+ "a.ASSIGNMENT,"
+ "a.STATUS,"
+ "to_char(a.CLOSE_TIME_EST,'DD-MON-YYYY hh24:mi:ss') CLOSE_TIME,"
+ "to_char(a.ELAPSED_TIME,'DD-MON-YYYY hh24:mi:ss') ELAPSED_TIME,"
+ "a.RESOLUTION_CODE,"
+ "a.TYPE,"
+ "a.OPEN_GROUP,"
+ "a.RESOLVED_GROUP,"
+ "to_char(a.RESOLVED_TIME,'DD-MON-YYYY hh24:mi:ss') RESOLVED_TIME,"
+ "a.USER_PRIORITY,"
+ "a.JP_ACCT_LOB,"
+ "a.JP_ACCT_APP_RTO,"
+ "a.JP_IMPACT,"
+ "a.jp_impact_duration_min,"
+ "a.JP_OUTAGE_DURATION_MIN,"
+ "a.JP_TTR_D1,"
+ "a.JP_TTR_D2,"
+ "a.JP_TTR_R1,"
+ "a.JP_TTR_R2,"
+ "a.JP_TTR_D2R2,"
+ "a.LOGICAL_NAME,"
+ "b.JP_EXTERNAL_ID,"
+ "b.JP_EXTERNAL_SYSTEM,"
+ "b.JP_CONFIG_ITEM,"
+ "b.JP_MASTER_HOST,"
+ "b.JP_SITE,"
+ "b.JP_APPSERVICE_NAME,"
+ "b.JP_APPSERVICE_ID,"
+ "b.JP_VERUMIDENTIFIER "
+ "FROM SCUSER.PROBSUMMARYM1 a LEFT JOIN SCUSER.DEVICEM1 b ON (DECODE(a.LOGICAL_NAME,b.LOGICAL_NAME,1,0)=1) "
+ "where a.SEVERITY_CODE IN ('P1/S1','P1/S2','P1/S3') "
+ "and a.CPR_BUSINESS_OPERATIONS = 'f' "
+ "and a.ASSIGNMENT like 'X%' "
+ "and (TRUNC(OPEN_TIME_EST) >=TRUNC(SYSDATE-30) OR TRUNC(CLOSE_TIME_EST) >=TRUNC(SYSDATE-30)) and (a.JP_CONFIDENTIAL IS NULL OR a.JP_CONFIDENTIAL= 'f')";
logger.info(cprSql);
return oracleJdbcTemplate.query(cprSql, new IncidentMapper());
The issue is when i am running these files in local i am able to get the data from oracle to mysql(MariaDB) but when i deploy the same in cloud(Gaia) I am getting a conflict. The Conflict is that the cprSql query in Repository class is connecting to mysql in gaia environment.
Below is the issue when i access the url
Mon Oct 15 12:21:49 UTC 2018
There was an unexpected error (type=Internal Server Error, status=500).
StatementCallback; bad SQL grammar [
SELECT a.NUMBERPRGN as INCIDENT_NUMBER,a.JP_ACCT_APP_APPID as APPLICATION_ID,
a.CATEGORY,to_char(a.OPEN_TIME_EST,'DD-MON-YYYY hh24:mi:ss') OPEN_TIME,
a.SEVERITY_CODE,a.ASSIGNMENT,a.STATUS,
to_char(a.CLOSE_TIME_EST, 'DD-MON-YYYY hh24:mi:ss') CLOSE_TIME,
to_char(a.ELAPSED_TIME, 'DD-MON-YYYY hh24:mi:ss') ELAPSED_TIME,
a.RESOLUTION_CODE, a.TYPE,a.OPEN_GROUP,a.RESOLVED_GROUP,
to_char(a.RESOLVED_TIME, 'DD-MON-YYYY hh24:mi:ss') RESOLVED_TIME,
a.USER_PRIORITY, a.JP_ACCT_LOB,a.JP_ACCT_APP_RTO,a.JP_IMPACT,
a.jp_impact_duration_min, a.JP_OUTAGE_DURATION_MIN,a.JP_TTR_D1,
a.JP_TTR_D2,a.JP_TTR_R1, a.JP_TTR_R2,a.JP_TTR_D2R2,a.LOGICAL_NAME,
b.JP_EXTERNAL_ID, b.JP_EXTERNAL_SYSTEM,b.JP_CONFIG_ITEM,b.JP_MASTER_HOST,
b.JP_SITE,b.JP_APPSERVICE_NAME,b.JP_APPSERVICE_ID,b.JP_VERUMIDENTIFIER
FROM SCUSER.PROBSUMMARYM1 a
LEFT JOIN SCUSER.DEVICEM1 b ON (DECODE(a.LOGICAL_NAME,b.LOGICAL_NAME,
1,0)=1
)
where a.SEVERITY_CODE IN ('P1/S1','P1/S2','P1/S3')
and a.CPR_BUSINESS_OPERATIONS = 'f'
and a.ASSIGNMENT like 'X%'
and (TRUNC(OPEN_TIME_EST) >=TRUNC(SYSDATE-30)
OR TRUNC(CLOSE_TIME_EST) >=TRUNC(SYSDATE-30)
)
and (a.JP_CONFIDENTIAL IS NULL
OR a.JP_CONFIDENTIAL= 'f'
)
]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Incorrect parameter count in the call to native function 'DECODE'
Could someone please help ..I am stuck with this from morning!!..

Constructor must be called super error in JSP, JDBC, servlet and forms

I'm creating a registration form for my web application and I'm getting the following error when I try to access register a new user:
java.lang.VerifyError: (class: eBooks/Data/UserDB, method: <init> signature: ()V) Constructor must call super() or this() java.lang.VerifyError: (class: eBooks/Data/UserDB, method: <init> signature: ()V) Constructor must call super() or this()
at eBooks.controller.RegisterUserServlet.doPost(RegisterUserServlet.java:62)
This is the UserDB class:
package eBooks.Data;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import eBooks.business.User;
import eBooks.util.DBUtil;
public class UserDB {
public static int insert(User user)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query =
"INSERT INTO User (fName, lName, email_address, password, dataOfBirth, phone,"
+ " address, city, state, country, zipcode, accountType)"
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?)";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, user.getfName());
ps.setString(2, user.getlName());
ps.setString(3, user.getEmailAddress());
ps.setString(4, user.getPassword());
ps.setString(5, user.getDateOfBirth());
ps.setString(5, user.getPhone());
ps.setString(6, user.getAddress());
ps.setString(7, user.getCity());
ps.setString(8, user.getCountry());
ps.setString(9, user.getState());
ps.setString(10, user.getZipcode());
//ps.setString(11, user.getAccountType()); -- Ask Jassin
return ps.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
return 0;
}
finally
{
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static int update(User user)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "UPDATE User SET"
+ "fName = ?"
+ "lName = ?"
+ "password = ?"
+ "dateOfBirth = ?"
+ "phone = ?"
+ "address = ?"
+ "city = ?"
+ "state_or_Region = ?"
+ "country = ?"
+ "zip = ?"
+ ""
+ "WHERE email_address= ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, user.getfName());
ps.setString(2, user.getlName());
ps.setString(3, user.getEmailAddress());
ps.setString(4, user.getPassword());
ps.setString(5, user.getDateOfBirth());
ps.setString(5, user.getPhone());
ps.setString(6, user.getAddress());
ps.setString(7, user.getCity());
ps.setString(8, user.getCountry());
ps.setString(9, user.getState());
ps.setString(10, user.getZipcode());
//ps.setString(11, user.getAccountType()); -- Ask Jassin
return ps.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
return 0;
}
finally
{
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static int delete(User user)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "DELETE FROM User" +
"WHERE email_address = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, user.getEmailAddress());
return ps.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
return 0;
}
finally
{
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static boolean emailExists(String emailAddress)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT email_address FROM User"+
"WHERE email_address = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, emailAddress);
rs = ps.executeQuery();
return rs.next();
}
catch(SQLException e)
{
e.printStackTrace();
return false;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static User selectUser(String emailAddress)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT * FROM User"+
"WHERE email_address = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, emailAddress);
rs = ps.executeQuery();
User user = null;
if (rs.next())
{
user = new User();
user.setfName(rs.getString("fName"));
user.setlName(rs.getString("lName"));
user.setEmailAddress(rs.getString("emailAddress"));
user.setPassword(rs.getString("password"));
user.setPhone(rs.getString("phone"));
user.setDateOfBirth(rs.getString("dateOfBirth"));
user.setAddress(rs.getString("address"));
user.setCity(rs.getString("city"));
user.setCountry(rs.getString("country"));
user.setState(rs.getString("state"));
user.setZipcode(rs.getString("zip"));
// user.setAccountType(rs.getString("accountType")); -- Ask Jassin
}
return user;
}
catch(SQLException e)
{
e.printStackTrace();
return null;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
}
This is the RegisterUserServlet:
package eBooks.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;
import eBooks.business.User;
import eBooks.business.Account;
import eBooks.Data.UserDB;
public class RegisterUserServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
HttpSession session = request.getSession();
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String emailAddress = request.getParameter("emailAddress");
String password = request.getParameter("password");
String dateOfBirth = request.getParameter("dateOfBirth");
String phone = request.getParameter("phohe");
String address = request.getParameter("address");
String city = request.getParameter("city");
String country = request.getParameter("country");
String state = request.getParameter("country");
String accountType = request.getParameter("accountType");
//TO DO: Account acctTypeList = request.getParameter("acctTypeList"); add this an object first
User user = new User();
user.setfName(fName);
user.setlName(lName);
user.setEmailAddress(emailAddress);
user.setPassword(password);
user.setDateOfBirth(dateOfBirth);
user.setAddress(address);
user.setCity(city);
user.setCountry(country);
user.setState(state);
user.setZipcode(phone);
//TODO: user.setAccountType(accTypeList); -- Ask Jassin
// Add information to the database
if(UserDB.emailExists(emailAddress))
UserDB.update(user);
else
UserDB.update(user);
session.setAttribute("User", user);
Cookie emailCookie = new Cookie("emailCookie", emailAddress);
emailCookie.setMaxAge(60*60*24*365*2);
emailCookie.setPath("/");
response.addCookie(emailCookie);
String url = "WEB-INF/view/registration_confirmation.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
I'm new to web development and I just need a push in the right direction to fix this issue.
I'm using glassfish and mysql.
Just fixed the problem – moved all the files to a new project and manually created the web.xml and it's is working fine now. Thanks #ErnestFriedman-Hill

org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object

I'm using Tomcat 7, MySql Workbench 5.2.27, JSF 2.0 and this exception comes from the ManagedBean(TripTableBean.java) of my web page(Trip Record.xhtml). It comes up whenever I click to go to Trip Record.xhtml after navigating through my other web pages. Pardon my horrible codes...
TripTableBean.java
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object
at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:114)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at Database.DBController.readRequest(DBController.java:21)
at Database.TripTableBean.retrieve(TripTableBean.java:389)
at Database.TripTableBean.<init>(TripTableBean.java:69)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:71)
at org.apache.el.parser.AstValue.getTarget(AstValue.java:94)
at org.apache.el.parser.AstValue.getType(AstValue.java:82)
at org.apache.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:176)
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:98)
at org.primefaces.component.datatable.DataTable.isLazy(DataTable.java:904)
at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:177)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:103)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:304)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The method where the exception originates : (TripTableBean.java:389) points to rs2 = db.readRequest(dbQuery2);
public void retrieve() throws SQLException, NamingException {
t = new ArrayList<TripSearchy>();
ResultSet rs = null;
ResultSet rs2 = null;
ResultSet rs3 = null;
DBController db = new DBController();
db.setUp();
//SQL: change select statement here
String dbQuery = "select * from (trip inner join agency on trip.id=agency.trip_id inner join tourguide on trip.id=tourguide.trip_id inner join accommodation on trip.id=accommodation.trip_id)";
rs = db.readRequest(dbQuery);
try{
while(rs.next()){
//add to list
id = rs.getInt("trip.id");
name = rs.getString("trip.name");
startDate = rs.getString("trip.startDate");
endDate = rs.getString("trip.endDate");
costOfTrip = rs.getString("trip.costOfTrip");
maxNoOfParticipants = rs.getString("trip.maxNoOfParticipants");
closingDateOfApplication = rs.getString("trip.closingDateOfApplication");
instructions = rs.getString("trip.instructions");
psea = rs.getString("trip.psea");
fasop = rs.getString("trip.fasop");
ktpiop = rs.getString("trip.ktpiop");
opId = rs.getInt("trip.overseasprogramme_id");
overseasProgramme = rs.getString("trip.overseasProgrammeName");
tourGuideName = rs.getString("tourguide.name");
tourGuideContact = rs.getString("tourguide.contact");
companyName = rs.getString("agency.companyName");
agentName = rs.getString("agency.agentName");
agentContact = rs.getString("agency.agentContact");
airlineChoice = rs.getString("agency.airlineChoice");
placeOfLodging = rs.getString("accommodation.placeOfLodging");
startDateOfLodging = rs.getString("accommodation.startDate");
endDateOfLodging = rs.getString("accommodation.endDate");
String dbQuery2 = "Select * from tripstaff where trip_id = '" + id + "'";
rs2 = db.readRequest(dbQuery2);
String lec;
ArrayList<String> dbQueryM = new ArrayList<String>();
while (rs2.next()){
lec = rs2.getString("tripstaff.lecturer_id");
dbQueryM.add("Select * from lecturer where id = '" + lec + "'");
}
ArrayList<NypStaff> nsf = new ArrayList<NypStaff>();
for (int i = 0; i < dbQueryM.size(); i++){
rs3 = db.readRequest(dbQueryM.get(i));
if (rs3.next()){
NypStaff temp = new NypStaff();
//set values retrieved from database into attributes
temp.setName(rs3.getString("lecturer.name"));
temp.setEmail(rs3.getString("lecturer.email"));
temp.setContact(rs3.getString("lecturer.contact"));
nsf.add(temp);
}
}
try {
Calendar c = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
Calendar c3 = Calendar.getInstance();
Calendar c4 = Calendar.getInstance();
Calendar c5 = Calendar.getInstance();
try {
c.setTime(formatter.parse(startDate));
c2.setTime(formatter.parse(endDate));
c3.setTime(formatter.parse(startDateOfLodging));
c4.setTime(formatter.parse(endDateOfLodging));
c5.setTime(formatter.parse(closingDateOfApplication));
}
catch (ParseException e1) {
e1.printStackTrace();
}
c.add(Calendar.DATE, 1);
c2.add(Calendar.DATE, 1);
c3.add(Calendar.DATE, 1);
c4.add(Calendar.DATE, 1);
c5.add(Calendar.DATE, 1);
startDate = formatter.format(c.getTime());
endDate = formatter.format(c2.getTime());
startDateOfLodging = formatter.format(c3.getTime());
endDateOfLodging = formatter.format(c4.getTime());
closingDateOfApplication = formatter.format(c5.getTime());
startDated = formatter.parse(startDate);
endDated = formatter.parse(endDate);
startDatedOfLodging = formatter.parse(startDateOfLodging);
endDatedOfLodging = formatter.parse(endDateOfLodging);
closingDatedOfApplication = formatter.parse(closingDateOfApplication);
c.add(Calendar.DATE, -1);
c2.add(Calendar.DATE, -1);
c3.add(Calendar.DATE, -1);
c4.add(Calendar.DATE, -1);
c5.add(Calendar.DATE, -1);
startDate = formatter.format(c.getTime());
endDate = formatter.format(c2.getTime());
startDateOfLodging = formatter.format(c3.getTime());
endDateOfLodging = formatter.format(c4.getTime());
closingDateOfApplication = formatter.format(c5.getTime());
}
catch (ParseException e1) {
e1.printStackTrace();
}
t.add(new TripSearchy (id, opId, overseasProgramme, name, startDated, startDate, endDated, endDate, costOfTrip, ns, nsf, staffName, tourGuideName, tourGuideContact, companyName, agentName, agentContact, airlineChoice, placeOfLodging, startDatedOfLodging, startDateOfLodging, endDatedOfLodging, endDateOfLodging, maxNoOfParticipants, closingDatedOfApplication, closingDateOfApplication, instructions, psea, fasop, ktpiop));
}
}catch (Exception e) {
e.printStackTrace();
}
db.terminate();
}
It seems that I have exhausted my connection =\ May I know how do I reduce my usage of the connection/increase the capacity of the connection?
Update:
DBController.java
public class DBController {
private DataSource ds;
Connection con;
public void setUp() throws NamingException{
//connect to database
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/it2299");
}
public ResultSet readRequest(String dbQuery){
ResultSet rs=null;
try{
con = ds.getConnection();
Statement stmt = con.createStatement();
rs = stmt.executeQuery(dbQuery);
}
catch(Exception e){e.printStackTrace();}
return rs;
}
public int updateRequest(String dbQuery){
int count=0;
try{
con = ds.getConnection();
Statement stmt = con.createStatement();
count=stmt.executeUpdate(dbQuery);
}
catch(Exception e){e.printStackTrace();}
return count;
}
public void terminate(){
try {con.close();}
catch(Exception e){e.printStackTrace();}
}
}
Update 2:
This exception occurs when the scope of my ManagedBean(TripTableBean.java) is ViewScoped, it doesn't occur when I change it to SessionScoped. However if it is SessionScoped, I'll need to find a way to kill session and recreate a new session whenever I come to this web page if not my dataTable on this page won't load updated changes from the database.
As you hinted yourself, your code is horrible. You need to ensure that all JDBC resources are acquired and closed in the shortest possibe scope in a try-finally block. Rewrite your code so that it follows the following standard JDBC idiom:
public List<Entity> list() throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List<Entity> entities = new ArrayList<Entity>();
try {
connection = Database.getConnection();
statement = connection.prepareStatement("SELECT id, foo, bar FROM entity");
resultSet = statement.executeQuery();
while (resultSet.next()) {
Entity entity = new Entity();
entity.setId(resultSet.getLong("id"));
entity.setFoo(resultSet.getString("foo"));
entity.setBar(resultSet.getString("bar"));
entities.add(entity);
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
return entities;
}
See also:
If I use a singleton class for a database connection, can one user close the connection for everybody?
JDBC MySql connection pooling practices to avoid exhausted connection pool
what are you connection pool settings can you post whats in DBController?
Tip: db.terminate() should be in finally{} block, may be you are lossing connections on exceptions.
Update:
Posting some of the modifications that might help you, but DO CLEAN UP THE CODE for maintenance sake. Look for comments where changes have been made.
public class DBController {
private DataSource ds;
private Connection con;// NEW CHANGE
public void setUp() throws NamingException{
//connect to database
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/it2299");
con = ds.getConnection(); // NEW CHANGE
}
public ResultSet readRequest(String dbQuery){
ResultSet rs=null;
try{
//REMOVED CODE FROM HERE
Statement stmt = con.createStatement();
rs = stmt.executeQuery(dbQuery);
}
catch(Exception e){e.printStackTrace();}
return rs;
}
public int updateRequest(String dbQuery){
int count=0;
try{
//REMOVED CODE FROM HERE
Statement stmt = con.createStatement();
count=stmt.executeUpdate(dbQuery);
}
catch(Exception e){e.printStackTrace();}
return count;
}
public void terminate(){
try {con.close();}
catch(Exception e){e.printStackTrace();}
}
}
Code cannot be improved beyond this by me, but I suggest have a look at some of the best practices over net and as suggested by #BalusC.
Remember: To close the connection object when done.

Hibernate's session.connection Error: "Too many users"

I am developing a Java web application using Hibernate, but there is a part of it where I want to use JDBC because I am creating look-up tables dynamically.
After a few minutes of using my web app I get this error:
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException:
Data source rejected establishment of
connection, message from server: "Too
many connections"
I know that using session.connection() is deprecated but I just want to get the underlying JDBC connection. I experimented using the session.doWork() but the error still occurred as it had before.
Here is what the code looks like:
Domain Layer:
/**
* Goes through the list of lookupTableAbstractions and persists each one
* #param lookupData
*/
public void updateLookupValues( List<LookupTableAbstraction> lookupData )
{
lookupTablesData.dropAllLookupTables(lookupData);
lookupTablesData.createLookupTables(lookupData);
for (LookupTableAbstraction lookupTable : lookupData)
lookupTablesData.persistLookupTableValues(lookupTable);
}
Data Layer:
public LookupTableAbstraction getLookupTable( String tableName )
{
LookupTableAbstraction lookupTable = new LookupTableAbstraction();
Session session = getSessionFactory().openSession();
String sqlQuery = "select value from " + tableName;
List<String> lookupTableValues = session.createSQLQuery(sqlQuery).list();
session.close();
lookupTable.setTableName(tableName);
for (String value : lookupTableValues)
lookupTable.addValue(value);
return lookupTable;
}
/**
* Persists the passed in lookup table.
* The lookup table that is used is determine by
* the tableName field of the passed in lookupTable
* #param lookupTable
*/
public void persistLookupTableValues( LookupTableAbstraction lookupTable )
{
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Connection connection = null;
try
{
connection = getJDBCConnectionFromHibernate(session);
Statement stmt = connection.createStatement();
String tableName = lookupTable.getTableName();
for (String value : lookupTable.getValues() )
{
String sql = " insert into " + tableName +
" (value) " +
" values " +
"('" + value + "')";
System.out.println(sql);
stmt.executeUpdate(sql);
}
stmt.close();
}
catch( Exception e )
{
System.out.println("Exception(persistLookupTableValues): " + e.getMessage());
e.printStackTrace();
}
finally
{
try {
tx.commit();
connection.close();
session.close();
} catch (SQLException e) {
System.out.println("Exception(persistLookupTableValues): " + e.getMessage());
e.printStackTrace();
}
}
}
/**
* Drop's all lookup tables.
* It drops each table based off the lookupTableAbstractions in the passed in list
* #param lookupData
*/
public void dropAllLookupTables( List<LookupTableAbstraction> lookupData )
{
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Connection connection = null;
try
{
connection = getJDBCConnectionFromHibernate(session);
Statement stmt = null;
for (LookupTableAbstraction lookupTableAbstraction : lookupData) {
stmt = connection.createStatement();
stmt.executeUpdate("drop table " + lookupTableAbstraction.getTableName());
}
stmt.close();
}
catch( Exception e )
{
System.out.println("Exception(dropAllLookupTables): " + e.getMessage());
e.printStackTrace();
}
finally
{
try {
tx.commit();
connection.close();
session.close();
} catch (SQLException e) {
System.out.println("Exception(dropAllLookupTables): " + e.getMessage());
e.printStackTrace();
}
}
}
/**
* Creates all lookup tables, one for each lookupTableAbstraction
* in the passed in list
* #param lookupData
*/
public void createLookupTables( List<LookupTableAbstraction> lookupData )
{
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Connection connection = null;
try
{
connection = getJDBCConnectionFromHibernate(session);
Statement stmt = null;
for (LookupTableAbstraction lookupTableAbstraction : lookupData) {
stmt = connection.createStatement();
stmt.executeUpdate("create table " + lookupTableAbstraction.getTableName() +
" ( ID int(11) auto_increment, " +
" value text, " +
" primary key (ID) )");
}
stmt.close();
}
catch( Exception e )
{
System.out.println("Exception(createLookupTables): " + e.getMessage());
e.printStackTrace();
}
finally
{
try {
tx.commit();
connection.close();
session.close();
} catch (SQLException e) {
System.out.println("Exception(createLookupTables): " + e.getMessage());
e.printStackTrace();
}
}
}
protected Connection getJDBCConnectionFromHibernate( Session session )
{
return session.connection();
}
Thanks for any suggestions
Same problem here. A lot of the examples on the internet forget to close out the session factory. If you don't close this out you will get the mysql "too many connections" error. Close it out with this line of code:
fact.close();
Assuming you named it fact like this:
SessionFactory fact = new Configuration().configure().buildSessionFactory();
I fixed the problem.
I was creating the session factory over and over.
So, I did this:
protected static SessionFactory sessionFactory = null;
static
{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
/**
* Returns a Hibernate session factory
* #return
*/
protected static SessionFactory getSessionFactory()
{
return sessionFactory;
}

PgSQL Exception: column name not found

I am using postgresql-8.3-603.jdbc4.jar with jdk 1.6 in my application to do the db operations. I am getting the below exceptions at sometimes and doing restart helps to avoid this exceptions temporarily.
org.postgresql.util.PSQLException: The column name sender_id was not found in this ResultSet.
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.findColumn(AbstractJdbc2ResultSet.java:2502)
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getString(AbstractJdbc2ResultSet.java:2345)
at org.apache.commons.dbcp.DelegatingResultSet.getString(DelegatingResultSet.java:225)
at org.apache.commons.dbcp.DelegatingResultSet.getString(DelegatingResultSet.java:225)
at com.netcore.bulkrequest.db.FeedDAO.setFeedDetails(FeedDAO.java:142)
at com.netcore.bulkrequest.feed.Feed.getInstance(Feed.java:37)
at com.netcore.bulkrequest.core.BulkRequestTask.(BulkRequestTask.java:86)
at com.netcore.bulkrequest.core.BulkRequestValidate.getBulkRequestTaskObject(BulkRequestValidate.java:104)
at com.netcore.bulkrequest.core.BulkRequestValidate.run(BulkRequestValidate.java:57)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Here is the code snippet:
public class FeedDAO {
/**
* Database connection pool object
*/
private final DBContext dbc;
private final Feed feed;
public static final String SENDER_ID_ATTRIBUTE = "sender_id";
/**
* Constructor
*
* #param dbc
* #param feed
*/
public FeedDAO(DBContext dbc, Feed feed) {
this.dbc = dbc;
this.feed = feed;
}
public void setFeedDetails() throws SQLException {
String feedDetailsQuery = "SELECT a.priority, b.keyword, b.welcome " +
" FROM feed AS a, pub_feed_info AS b " +
" WHERE a.resource_id = b.resource_id AND b.resource_id = ?";
String senderIdQuery = "SELECT b.attribute_value AS " +
SENDER_ID_ATTRIBUTE + " FROM " +
"attribute_master AS a, feed_attributes AS b " +
"WHERE a.attribute_id = b.attribute " +
" AND a.attribute_name='" + SENDER_ID_ATTRIBUTE + "' " +
" AND feed_id = ?";
Connection con = null;
PreparedStatement fdStmt = null;
PreparedStatement siStmt = null;
try {
con = dbc.getConnection();
//Get the feed details
fdStmt = dbc.getPreparedStatement(con, feedDetailsQuery);
fdStmt.setInt(1, this.feed.getFeedId());
fdStmt.execute();
ResultSet fdResults = fdStmt.getResultSet();
while (fdResults.next()) {
String keyword = fdResults.getString("keyword");
String welcomeMsg = fdResults.getString("welcome");
int priority = fdResults.getInt("priority");
if(null != keyword) {
this.feed.setKeyword(keyword);
} else {
this.feed.setKeyword(String.valueOf(this.feed.getFeedId()));
}
this.feed.setWelcomeMsg(welcomeMsg);
this.feed.setPriority(priority);
}
//Get the sender id
siStmt = dbc.getPreparedStatement(con, senderIdQuery);
siStmt.setInt(1, this.feed.getFeedId());
if(siStmt.execute()) {
ResultSet siResults = siStmt.getResultSet();
while(siResults.next()) {
String senderId = siResults.getString(SENDER_ID_ATTRIBUTE);
this.feed.setSenderId(senderId);
}
} else {
this.feed.setSenderId(Feed.DEFAULT_SENDER_ID);
}
} catch (SQLException ex) {
throw ex;
} finally {
if (fdStmt != null) { fdStmt.close(); }
if (siStmt != null) { siStmt.close(); }
if (con != null) { con.close(); }
}
}
}
Can anyone please help me to find the permanent fix?
Thanks,
Mani
The key part of the error is "The column name sender_id was not found in this ResultSet" -- te very first row. So, how about showing us the query that's looking for a column that's just not there, and maybe the results of executing that query interactively in pgsql, the relevant parts of your schema, etc? Surely you can't expect us to help you debug without seeing anything more than the exception traceback, with zero clues about your code and DB!