Spring transaction issue with tomcat, mysql and eclipselink - mysql

I've got lot of confusions after googling for spring transactions with eclipselink, tomcat and mysql. Please consider the following questions and guide me on this topic.
Can i run spring transactions with eclipseLink, tomcat and mysql enviornment? if so how is the config? i have used the following config and i get lock exceptions always.
Persistence.xml:
<persistence-unit name="xxxxService" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>...</class>
<class>...</class>
<class>...</class>
<properties> .... </properties>
</persistence-unit>
Spring-beans.xml:
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" />
</bean>
<bean
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect" ref="jpaDialect" />
<property name="persistenceUnitName" value="xxxxService" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
JAVA class:
#Transactional
public void saveSumthg(Sumthg sumthg) throws Exception{
someDAO.saveSumthg(sumthg);
}
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public List<Sumthg> findActiveSumthgs(String username) {
List<Sumthg> sumthgs = someDAO.findActiveSumthgs(username);
return sumthgs ;
}
Am i doing anything wrong here? I'm not sure whether spring transaction handling works correctly with tomcat since i'm not using JTA transactions.
With EclipseLInk and mysql, Id generation strategy goes with Sequence table and in the table only one row is updated for all transactions. I suspect that this causes lock issues. Am i correct? If so, how can i avoid this?
ID generation config in a Domain class is like this:
#Id
#Column(name = "some_id", unique = true, nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
In mysql schema, a new table named SEQUENCE is created and a value is stored in it. Each time when a row is inserted, the id is taken from here i think. Since the same value is read and updated, i suspect that this can cause locking issues.
If i'm correct, how can i avoid this issue??
Looking forward for your answers.
Thanks.
got an update - i can see the following is logs:
Internal Exception: java.sql.SQLException: Lock wait timeout exceeded; try restarting
transaction
Error Code: 1205
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [50, SEQ_GEN]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT =
SEQ_COUNT + ? WHERE SEQ_NAME = ?")]
So it is clear that this is happening because the same value in SEQUENCE table is being modified by several threads. What is the best ID generation strategy i can use in this context??

The problem is that you are using the worst concurrent ID GENERATION solution (TABLE_SECUENCE).
In this case the best solution is to use the SEQUENCE GENERATION.
The sequencers handle much better the concurrency.

I can't see how you would get lock exceptions always. Are you running multiple threads/clients? Try setting logging on finest to see what is going on.
EclipseLink will normally allocate sequence ids outside of the transaction, so would normally not have any locking conflicts. You can also enable a sequence connection pool in EclipseLink that will always use a seperate connection for allocating ids to avoid any locking conflicts.

Related

REP-56132 Access is denied to the report definition file

I have been researching this problem for a couple weeks now and at a dead end.
Running 12c form and reports, Linux OEL 6, WebLogic 12c. Also, this is a 6i to 12c migration of all objects. This fails when sending the report directly across in the URL and with web.show_document.
Have added the COMPONENT_CONFIG_PATH, added the suggested changes to rwserver.conf and the rwservlet.properties, all folders and objects are wide open at 0777. I've tried a number of different users with various privileges but all have resulted in the same error. I have tried with RUN_REPORT_OBJECT and that also results in an error of FRM-41219. Here is the rwserver.confg:
<?xml version="1.0" encoding="UTF-8"?>
<server xmlns="http://xmlns.oracle.com/reports/server" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<cache class="oracle.reports.cache.RWCache">
<property name="cacheSize" value="50"/>
</cache>
<engine class="oracle.reports.engine.EngineImpl" engLife="1" id="rwEng" maxEngine="1" minEngine="1" maxIdle="3" callbackTime="90000">
<property name="sourceDir" value="/app01/bcis/forms"/>
<property name="tempDir" value="/app01/oracle/tmp"/>
<property name="keepConnection" value="yes"/>
</engine>
<engine class="oracle.reports.urlengine.URLEngineImpl" engLife="50" id="rwURLEng" maxEngine="1" minEngine="0"/>
<!--
<destination class="oracle.reports.server.DesFile" destype="file"/>
<destination class="oracle.reports.server.DesCache" destype="cache"/>
<destination class="oracle.reports.server.DesPrint" destype="printer"/>
-->
<destination class="oracle.reports.plugin.destination.ftp.DesFTP" destype="ftp"/>
<destination class="oracle.reports.plugin.destination.webdav.DesWebDAV" destype="WebDav"/>
<!--job engineId="rwEng" jobType="report" securityId="Empty"/-->
<!--job engineId="rwURLEng" jobType="rwurl" securityId="Empty"/-->
<notification class="oracle.reports.server.MailNotify" id="mailNotify">
<property name="succnotefile" value="succnote.txt"/>
<property name="failnotefile" value="failnote.txt"/>
</notification>
<jobRepository>
<property name="dbuser" value="rwadmin"/>
<property name="dbpassword" value="csf:reports:repo"/>
<property name="dbconn" value="dcis2d01.mlgw.org:1522:CISDB12"/>
</jobRepository>
<connection idleTimeOut="30" maxConnect="250"/>
<queue maxQueueSize="1000"/>
<folderAccess>
<read>/app01/bcis/forms:/app01/bcis/reports:/app01/bcis/dev/exe:/app01/bcis/exe:/app01/oracle/tmp</read>
<write>/app01/bcis/forms:/app01/bcis/reports:/app01/bcis/dev/exe:/app01/bcis/exe:/app01/oracle/tmp</write>
<defaultWriteFolder>/app01/bcis/forms</defaultWriteFolder>
</folderAccess>
<identifier encrypted="yes">QgZSFEalKUbL0t/KwwqSEg0=</identifier>
<proxyInfo>
<proxyServers>
<proxyServer name="$$Self.proxyHost$$" port="$$Self.proxyPort$$" protocol="all"/>
</proxyServers>
<bypassProxy>
<domain>$$Self.proxyByPass$$</domain>
</bypassProxy>
</proxyInfo>
<pluginParam value="%MAILSERVER_NAME%" name="mailServer"/>
</server>
The naming service:
<namingService name="Cos" host="10.211.212.164" port="14021"/>
I have checked the spelling of all paths, so they are right and they do run under rwrun and I can bring them up in rwbuilder.
If there is anything else that would be helpful, please let me know.
Any suggestions at this point will be helpful and I would appreciate as many quick responses as possible.
Have you added the report as an object in the calling form? (Similar to adding a new canvas or new datablock)
The find_report_object call should be passed the name of the report object as it was added to the form. The FRM-41219 makes me think you haven't added the report object. This did not need to be done in 6i.
Have you tried to verify that the reports are generated? You could try trigger generation of a report directly from a curl command on the reports server. I use something like the below URL to verify that the reportsserver is running:
http://reportsserver:port/reports/rwservlet?userid=user/password#tnsname&destype=cache&report=reportnam.rdf&desformat=PDF&argument1=123&argument2=456

Use Hibernate Annotation on databean: Cannot add constraint to MySQL table

I try to add constraints to MySQL table via databeans using hibernate annotation:
package databean;
import javax.persistence.*;
#Entity
#Table(name = "ADMIN",
uniqueConstraints = {
#UniqueConstraint(columnNames = "userName"),
#UniqueConstraint(columnNames = "email")
})
public class AdminBean {
// Private fields
#Id #GeneratedValue
#Column(name = "adminId")
private int adminId; // PK
#Column(name = "userName")
private String userName;
I also have 2 xml files for mapping: hibernate.cfg.xml and Admin.hbm.xml
1)
mapping resource="hibernate/Admin.hbm.xml"/
2)
<hibernate-mapping>
<class name="databean.AdminBean" table="ADMIN">
<meta attribute="class-description">
This class contains the admin detail.
</meta>
<id name="adminId" type="int" column="adminId">
<generator class="native"/>
</id>
<property name="userName" column="userName" type="string"/>
<property name="firstName" column="firstName" type="string"/>
<property name="lastName" column="lastName" type="string"/>
<property name="email" column="email" type="string"/>
<property name="phone" column="phone" type="string"/>
<property name="password" column="password" type="string"/>
<property name="city" column="city" type="string"/>
<property name="zipCode" column="zipCode" type="string"/>
</class>
</hibernate-mapping>
According to what I've found online:
"So far you have seen how Hibernate uses XML mapping file for the transformation of data from POJO to database tables and vice versa. Hibernate annotations is the newest way to define mappings without a use of XML file. You can use annotations in addition to or as a replacement of XML mapping metadata. Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code this helps the user to understand the table structure and POJO simultaneously during the development." (http://www.tutorialspoint.com/hibernate/hibernate_annotations.htm)
If I comment out the xml files mapping, I will get the exception of "Unknown entity: databean.AdminBean". Cannot even find the databean now.
Question:
1) Shouldn't the databean with hibernate annotations work even if there is no mapping in xml file? (So it does not even work now...)
2) If there is no hibernate annotation with databean, should I add constraints directly into the xml mapping file?
3) What is the best way to add constraints to MySQL tables? Since they are all automatically created when I run the application, it doesn't seem to make much sense to add constraints by building tables manually in mySQL first?
4) Is it really necessary to add constraints to both databean and (maybe) xml files?
Update:
Even when I try to set the property in xml file, mySQL database seems not to be able to "catch the constraints" and tables can still add duplicates items.
Now I doubt it might not be a problem with the way I add those constraints, but more like a "disconnection" with mySQL table and my code...though other parts can function pretty well. Anyone has faced similar situations before?
I find the reason: I did not drop the previous table when there is no constraint added when it is first created automatically by my app. Hope no one makes the same mistake. :)

Issue while saving Non-English character

We are working with one application where we need to save data in language Gujarati.
Technologies used in Applcation is listed below.
Spring MVC Version 4.1.6.RELEASE
Hibernate Version 4.3.5.Final
MySQL 6.0.11
My JSP is configured with
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
And
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
Hibernate configuration is
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.connection.characterEncoding">UTF-8</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
MySQL URL is
jdbc:mysql://host:port/dbName?useUnicode=true&connectionCollation=utf8_general_ci&characterSetResults=utf8
Pojo having String field to store that data.
MySQL have VARCHAR datatype to store data with charset=utf8 and Collation=utf8_general_ci
When i tried to save any non-english(Gujrati) character it show some garbage character like àª?à«?àª? for "ગુજ".
Is there any other configuration which i missed here.
I was facing the same problem while inserting "tamil" characters into the database.After surfing a lot I got a better and working solution and it solves my problem.Here I am sharing my solution with you.I hope it will help you to clear your doubts regarding that Non English character.
INSERT INTO
STUDENT(name,address)
VALUES
(N'பெயர்', N'முகவரி');
I am using a sample since you have not provided me any structure of your table and field name.
I am assuming you want ગુજ (GA JA with Vowel sign U)?
I think you somehow specified "latin5". (Yes I see you have UTF-8 everywhere, but "latin5" is the only way I can make things work.)
CONVERT(CONVERT(UNHEX('C3A0C2AAC297C3A0C2ABC281C3A0C2AAC29C')
USING utf8) USING latin5) = 'ગુજ'
Plus you ended up with "double encoding"; I suspect this is what happened:
The client had characters encoded as utf8 (good); and
SET NAMES latin5 was used, but it lied by claiming that the client had latin5 encoding; and
The column in the table declared CHARACTER SET utf8 (good).
If possible, it would be better to start over -- empty the tables, be sure to have SET NAMES utf8 or establish utf8 when connecting from your client to the database. Then repopulate the tables.
If you would rather try to recover the existing data, this might work:
UPDATE ... SET col = CONVERT(BINARY(CONVERT(
CONVERT(UNHEX(col) USING utf8)
USING latin5)) USING utf8);
But you would need to do that for each messed up column in each table.
A partial test of that code is to do
SELECT CONVERT(BINARY(CONVERT(
CONVERT(UNHEX(col) USING utf8)
USING latin5)) USING utf8)
FROM table;
I say "partial test" because looking right may not prove that is right.
After the UPDATE, SELECT HEX(col) get E0AA97E0AB81E0AA9C for ગુજ. Note that most Gujarati hex should be of the form E0AAyy or E0AByy. You might also find 20 for a blank space.
I apologize for not being more certain. I have been tackling Character Set issues for a decade, but this is a new variant.
There might be a couple of things that you could have missed out. I had the same problem with mysql on linux, what I had to do is to edit my.cnf like this:
[client]
default-character-set = utf8
[mysqld]
character-set-server = utf8
For e.g. on Centos this file is location at /etc/my.cnf on Windows (my pc) C:\ProgramData\MySQL\MySQL Server 5.5\my.ini. Please note that ProgramData might be hidden.
Also the other thing if you are using Tomcat is that you have to sepcify UTF-8 for URI encoding. Just edit server.xml and modify your main Connector element:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
URIEncoding="UTF-8"
redirectPort="8443" />
Also make sure you added character encoding filter in your application:
#WebFilter(filterName = "CharacterEncodingFilter", urlPatterns = {"/*"})
public class CharacterEncodingFilter implements Filter {
#Override
public void init(FilterConfig filterConfig)
throws ServletException {
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
request.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/html; charset=UTF-8");
filterChain.doFilter(request, servletResponse);
}
#Override
public void destroy() {
}
}
Hope this helps.
Another tip, don't lean only on setting the characterEncoding as a hibernate property <prop key="hibernate.connection.characterEncoding">UTF-8</prop>, make sure you add it explicitely as connection variable on the DB url, so
jdbc:mysql://host:port/dbName?useUnicode=true&characterEncoding=UTF-8&connectionCollation=utf8_general_ci&characterSetResults=utf8
Also, as there is some many layers where an encoding would be lost, you can try to isolate the layer and update to a question. E.g. if its upon storing to DB, or at some point before
Your applicationContext file should be like this:
To make Spring MVC application supports the internationalization, register two beans :
SessionLocaleResolver
Register a “SessionLocaleResolver” bean, named it exactly the same characters “localeResolver“. It resolves the locales by getting the predefined attribute from user’s session.
Note
If you do not register any “localeResolver”, the default AcceptHeaderLocaleResolver will be used, which resolves the locale by checking the accept-language header in the HTTP request.
LocaleChangeInterceptor
Register a “LocaleChangeInterceptor” interceptor and reference it to any handler mapping that need to supports the multiple languages. The “paramName” is the parameter value that’s used to set the locale.
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language" />
</bean>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
<!-- Register the bean -->
<bean class="com.common.controller.WelcomeController" />
<!-- Register the welcome.properties -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="welcome" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
The native2ascii is a handy tool build-in in the JDK, which is used to convert a file with ‘non-Latin 1′ or ‘non-Unicode’ characters to ‘Unicode-encoded’ characters.
Native2ascii example
Create a file (source.txt)
Create a file named “source.txt”, put some Chinese characters inside, and save it as “UTF-8″ format.
native2ascii
Use native2ascii command to convert it into Unicode format.
C:>native2ascii -encoding utf8 c:\source.txt c:\output.txt
The native2ascii will read all the characters from “c:\source.txt” and encode it with “utf8″ format, and output all encoded characters to “c:\output.txt”
Read Output
Open the “c:\output.txt”, you will see the all encoded characters, e.g \ufeff\u6768\u6728\u91d1
welcome.properties
welcome.springmvc = \u5feb\u4e50\u5b66\u4e60
Call the above string and store the value in database.
And if you want to display that inside JSP page:
Remember add the line
“<%# page contentType=”text/html;charset=UTF-8″ %>”
on top of the jsp page, else the page may not able to display the UTF-8
(Chinese) characters properly.

org.hibernate.MappingException: Unknown entity when trying to save POJO

I get the below error when I invoke the method to save an entity to the database.
ERROR: org.aggu.sramam.exceptions.SramamException - Exception thrown:
org.hibernate.MappingException: Unknown entity: org.aggu.sramam.pojo.SramaSangham
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1443
The POJO object is there in the package, and I also have the below entry in my hibernate-cfg.xml file
<hibernate-configuration>
<!-- List out the entities (i.e POJO linked to DB table) here -->
<session-factory>
<mapping class="org.aggu.sramam.pojo.SramaSangham" />
</session-factory>
</hibernate-configuration>
Below is the entry in the servlet-config.xml file, which gives the code base links
<!-- The below is the base package for all Sramam apps -->
<context:component-scan base-package="org.aggu.sramam" />
What have I missed here? I have added the #Entity, #Table, #Id tags etc. in the POJO object. There is an Unqiue ID column (Primary key), but I have not written any explicit code to generate the ID automatically. Would that be a problem?
Okay. Figured this out myself. The issue was that in my servlet-context.xml file, I had NOT given a reference/link to the hibernate.cfg.xml. Once this was given, the error got resolved and records started getting inserted.
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
<beans:prop key="hibernate.dialect">${jdbc.dialect}</beans:prop>
</beans:props>
</beans:property>
**<!- This line did the trick -->
<beans:property name="configLocation">
<beans:value>WEB-INF/classes/hibernate.cfg.xml</beans:value>
</beans:property>**
</beans:bean>

Too many connections using Hibernate and mysql

I am using Hibernate 3 and mysql sever 5.5 for myweb application with spring 3.0
I am getting exception as Too many connections......
My java file where I create session is as follows:
public class DBConnection {
static{
}
public Session getSession(){
Session session = null;
SessionFactory sessionFactory= null;
sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
return session;
}
}
and I call this method where I need session
as
Session session=new DBConnection().getSession();
and after
transaction.commit();
I close session by using
session.close();
please help me in solving problem.......
my hibernate.cfg.xml is :
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/dbname</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">lax</property>
<property name="hibernate.connection.pool_size">100</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name=""></property>
<property name="hibernate.connection.release_mode">on_close</property>
</session-factory>
</hibernate-configuration>
This is because you are using a connection pool which got created as soon as you build SessionFactory, but the connections are acquired only when you open a Session. Now, you are closing the session, due to which connections are released, but are not closed and are held up by the pool. Now, you are again creating a SessionFactory, hence creating a new pool, then getting a session, hence creating a new connection and so on.. which will eventually reach the maximum number of connections allowed.
What you have to do is using one Connection Pool (using one SessionFactory) and getting and releasing the connections from the same pool.
public class DBConnection {
private static SessionFactory factory;
static {
factory = new Configuration().configure().buildSessionFactory();
}
public Session getSession() {
return factory.openSession();
}
public void doWork() {
Session session = getSession();
// do work.
session.close();
}
// Call this during shutdown
public static void close() {
factory.close();
}
}
You create new SessionFactorys every time you need a Session and don't close them.
Usually you need to create session factory only once during startup of your application, and close it during shutdown. For example, as follows:
public class DBConnection {
private static SessionFactory factory;
static {
factory = new Configuration().configure().buildSessionFactory();
}
public Session getSession() {
return factory.openSession();
}
// Call this during shutdown
public static void close() {
factory.close();
}
}
Also take a look at contextual sessions pattern.
I have used
Session session = SessionFactoryUtils.getSession(this.sessionFactory,
true);
to get session. Above the DAO layer, transaction with annotations (#Transactional) is used in add, edit or delete. Our application uses shiro for authentication and authorization. In each page access, it creates at least 5 connections. So the subsequent request keeps on increasing mysql connection. Thanks to #Venu I found out that
show variables like "max_connections";
shows default maximum connection available. Initially (I guess) it was set to 151. This number would soon exhaust because another variable "innodb_open_files" was set to 300. By intuition I can say if one table reaches maximum connection of 300 it would only go for clean up (just like garbage collection in java).
One would think, if we would increase the value of "max_connections" to 300 it solve this error, but as I said earlier "innodb_open_files" does not go for cleanup until one table reaches that limit. In our case user table which would be called frequently would reach that limit for cleanup to happen. This means, you cannot know before hand what is the perfect number for "max_connections".
In mysql configuration file "/etc/mysql/my.cnf" max_connections is set as
max_connections = 1000
I did not change
value of "innodb_open_files", which is default to "300"
mysql> show variables like "innodb_open_files";
During execution of your program you can use
mysql> show processlist;
to find out how many connections are open. I guess all the processes in Sleep state can be deleted in next cycle of cleanup (but its only my guess).
To simulate more than 1000 users, executing some url in your web project, you can use software like jmeter and set number of thread (users) to 1000. Use of more user also depends upon available RAM in your computer. I was able to simulate more than 3000 connections sending requests at 1 second interval. A good and sufficient tutorial on how to do this is listed on roseindia
Now my query. I have not closed session on any place. I guess #Transaction was created for that purpose (mysql proves that, because all those connections get cleaned once the limit reaches). Due to merge problem of detached objects, I had to used OpenSessionInViewFilter. OpenSessionInViewFilter (can be OpenSessionInViewInterceptor) opens the session a little longer for the merge to happen, which might be the reason so many connections remain open in mysql (Don't know clearly). Since it works for so many users it seems a good solution, but is there a better solution to make it work under default max connection size of mysql. i.e 151 connections.
I was facing the same issues with Hibernate mysql conenctions
The following two things helped fix my connection problems
import javax.inject.Singleton;
#Singleton
public class DBConnection {
private static SessionFactory factory;
static public Session getSession() {
if (factory == null) {
System.out.println("--------New connection----");
factory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(SomeClass.class)
.buildSessionFactory();
}
//System.out.println("--------old connection----");
return factory.openSession();
}
// Call this during shutdown
public static void close() {
factory.close();
}
}
Create a singleton class for getting a DBConnection
Do not forget to perform session.close() when your query is complete
Also in "hibernate.cfg.xml"
add this line
<hibernate-configuration>
<session-factory>
....
<property name="connection.pool_size">100</property>
....
</session-factory>
</hibernate-configuration>
under
JAVA ISSUE
Please check this answer : https://stackoverflow.com/a/10785770/598424
MYSQL ISSUE
YOU NEED TO LOGIN AS SUPERUSER. THEN EXECUTE THIS CODE:
SET GLOBAL MAX_CONNECTIONS = 200;
HOWEVER, THIS ONLY LASTS UNTIL THE MYSQL SERVER RESTARTS. IF YOU WANT TO CHANGE IT PERMANENTLY, YOU CAN ADD THE FOLLOWING LIKE UNDER MYSQLD SECTION.
MAX_CONNECTIONS = 500
OR
IF YOU HAVE TOO MANY PROCESSES LINGERING AROUND ON THE DATABASE SERVER, THEN YOU MAY REACH A LIMIT AND NO NEW ONES WILL BE ALLOWED TO BE STARTED.
To see if this is the case, take a look at your processes from the MySQL Monitor prompt by typing:
show processlist;
Then you will see the lingering processes. Each has an ID, and you can kill them by process ID right in the MySQL Monitor by typing:
kill 2309344;