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

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;
}

Related

How do I work with aws rds myql on eclipse(Java)?

I have downloaded aws sdk and connected my account and the database. But now I do not know what I need to do next. How do insert, delete or create table through java on eclipse.
I know to do these in a local database. I tried changing the url in getConnection() function to the my endpoint on eclipse but I keep getting error stating
"Access denied for user 'aws'#'xxx.xxx.xxx.xxx' (using password: YES)" (real IP modified for security reasons).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class MySQLAccess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private static final String url = "jdbc:mysql://aws.cyduxshnlizb.ap-south-1.rds.amazonaws.com:3306";
final private String user = "myusername";
final private String passwd = "mypassword";
public void readDataBase() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection(url,user,passwd);
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("select * from feedback.comments");
writeResultSet(resultSet);
// PreparedStatements can use variables and are more efficient
preparedStatement = connect
.prepareStatement("insert into feedback.comments values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from feedback.comments");
// Parameters start with 1
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "TestEmail");
preparedStatement.setString(3, "TestWebpage");
preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
preparedStatement.setString(5, "TestSummary");
preparedStatement.setString(6, "TestComment");
preparedStatement.executeUpdate();
preparedStatement = connect
.prepareStatement("SELECT myuser, webpage, datum, summary, COMMENTS from feedback.comments");
resultSet = preparedStatement.executeQuery();
writeResultSet(resultSet);
// Remove again the insert comment
preparedStatement = connect
.prepareStatement("delete from feedback.comments where myuser= ? ; ");
preparedStatement.setString(1, "Test");
preparedStatement.executeUpdate();
resultSet = statement
.executeQuery("select * from feedback.comments");
writeMetaData(resultSet);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void writeMetaData(ResultSet resultSet) throws SQLException {
// Now get some metadata from the database
// Result set get the result of the SQL query
System.out.println("The columns in the table are: ");
System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
for (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
System.out.println("Column " +i + " "+ resultSet.getMetaData().getColumnName(i));
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("myuser");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Website: " + website);
System.out.println("Summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
}
// You need to close the resultSet
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
}

DataStore: Exception: Column count doesn't match value count at row 1

I am getting the error as per the heading and am totally at a lose as to why.
public static int addSkill( String code ) {
PreparedStatement insertSkill = null;
int result = 0;
Connection connection = null;
try {
connection = database.connect(null, null);
insertSkill = connection.prepareStatement( "INSERT INTO Skill VALUES (0,?)" );
/* *Set the wild cards of the prepared statement insertSkill */
insertSkill.setString( 1, code );
result = insertSkill.executeUpdate();
} // try()
catch ( java.sql.SQLIntegrityConstraintViolationException insert ) {
// This catches a problem of inserting a duplicate skill.
// If it occurs, the method will return 0 (initial value of result).
log.errorMessage("DataStore: Exception: " + insert.getMessage());
} // catch()
catch ( SQLException sqlException ) {
log.errorMessage("DataStore: Exception: " + sqlException.getMessage());
} // catch()
finally{
if(connection !=null){
try {
connection.close();
}
catch (SQLException e) {
log.errorMessage("Connction failed to return to the pool\n");
e.printStackTrace();
}
}
}
return result;
}// addSkill()

Getting GWT error while trying to update userinformation stored in mySql

im getting this error - "java.sql.SQLException: Parameter index out of range (6 > number of parameters, which is 5)".
Im trying to update information about my user - trough GWT and MySql - of course
public boolean changePersonInfo(Person person) throws IllegalArgumentException {
try {
PreparedStatement updatePerson = connection.prepareStatement("UPDATE users SET " + "adgangskode = ?, "
+ "email = ?, " + "alder = ?, " + "tlfnr = ?, " + "WHERE id = ?");
updatePerson.setString(1, person.getPassword());
updatePerson.setString(2, person.getEmail());
updatePerson.setString(3, person.getAge() + "");
updatePerson.setString(4, person.getPhonenumber());
updatePerson.setInt(5, person.getId());
int rowsAffected = updatePerson.executeUpdate();
if (rowsAffected == 1) {
return true;
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return false;
Also have this function that should talk with my clickhandler - and RpcServiceImpl
class SettingsClickhandler implements ClickHandler{
#Override
public void onClick(ClickEvent event) {
currentPerson.setPassword(userView.getSettingsView().getPassBoxChange().getText());
currentPerson.setEmail(userView.getSettingsView().getEmailBoxChange().getText());
currentPerson.setAge(Integer.valueOf(userView.getSettingsView().getAgeChangeBox().getText()));
currentPerson.setPhonenumber(userView.getSettingsView().getTlfChangeBox().getText());
// The RPC call which through the server updates the user info in the users table in the database
Service.changePersonInfo(currentPerson, new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable caught) {
}
/*
* Confirmation if the info was updated
*/
#Override
public void onSuccess(Boolean isUpdated) {
if (isUpdated) {
content.getUserView().getSettingsView();
userView.getSettingsView().clearTextBoxFields();
Window.alert("Aendring lykkes");
}else{
userView.getSettingsView();
Window.alert("Aendring Mislykkes");
}

Hibernate in JSF Social Application runs out of connections

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.

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!