Seems like Hibernate exceeds connection limit - java

Can anybody help me solve this situation?
I have a Tomcat and simple JSF Application: https://github.com/gooamoko/jsfbilling/.
When I run application on Tomcat, it runs normally, but after several requests (for example 10 quick refresh page) raise the exception can't open connection.
I think, it's normal, but where is the mistake?
In the configuration file hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/netstat</property>
<property name="connection.username">netstat</property>
<property name="connection.password">netstat</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- configuration pool via c3p0 -->
<property name="c3p0.min_size">5</property>
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">200</property>
<property name="c3p0.timeout">600</property> <!-- seconds -->
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping classes -->
<mapping class="ru.gooamoko.model.Group" />
<mapping class="ru.gooamoko.model.Host" />
<mapping class="ru.gooamoko.model.Traffic" />
<mapping class="ru.gooamoko.model.DailyTraffic" />
</session-factory>
</hibernate-configuration>
or in the Java classess
package ru.gooamoko.dao;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateProvider {
private static SessionFactory factory;
private static ServiceRegistry registry;
public static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
registry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
factory = configuration.buildSessionFactory(registry);
return factory;
}
}
package ru.gooamoko.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class GenericDao {
private SessionFactory factory;
protected Session session;
protected void begin() {
session = factory.getCurrentSession();
session.beginTransaction();
}
protected void commit() {
if (session.isOpen()) {
session.getTransaction().commit();
}
}
protected void rollback() {
if (session.isOpen()) {
session.getTransaction().rollback();
}
}
public GenericDao() {
this.factory = HibernateProvider.getSessionFactory();
}
}
In the tomcat log I see this
27-Aug-2014 15:06:24.559 WARNING [C3P0PooledConnectionPoolManager[identityToken->1hge12w9467h4hm1tfa5tj|3b40a97d]-HelperThread-#2] com.mchange.v2.resourcepool.BasicResourcePool.forceKillAcquires Having failed to acquire a resource, com.mchange.v2.resourcepool.BasicResourcePool#4df5a3a4 is interrupting all Threads waiting on a resource to check out. Will try again in response to new client requests.
27-Aug-2014 15:06:24.563 WARNING [C3P0PooledConnectionPoolManager[identityToken->1hge12w9467h4hm1tfa5tj|3b40a97d]-HelperThread-#2] com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask#628977a2 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
org.postgresql.util.PSQLException: ?????: ?????????? ????? ??????????? ??????????????? ??? ??????????? ????????????????? (?? ??? ??????????)
at org.postgresql.core.v3.ConnectionFactoryImpl.readStartupMessages(ConnectionFactoryImpl.java:572)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:177)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:64)
at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:136)
at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:29)
at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:21)
at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:31)
at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:24)
at org.postgresql.Driver.makeConnection(Driver.java:393)
at org.postgresql.Driver.connect(Driver.java:267)
at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:146)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:195)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:184)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)
How and where should I correct close open connections?
Thanks for wasting your time for me.

I've read Hibernate documentation and found example of HibernateUtil class.
After comparing with my HibernateProvider I found, that seems like in my HibernateProvider Factory was build every call of getSessionFactory(). New version of HibernateProvider is
package ru.gooamoko.dao;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateProvider {
private static final SessionFactory factory = buildFactory();
public static SessionFactory getSessionFactory() {
return factory;
}
private static SessionFactory buildFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
return configuration.buildSessionFactory(registry);
} catch (HibernateException ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
}
So, now query
SELECT COUNT(*) FROm pg_stat_activity;
returns 6, one of which is psql client. Even after minute of re-requesting page. I think, it's a progress.
The only one thing remains - is to make possible for Hibernate work with postgresql-jdbc.jat in Tomcat /lib folder and no use jar in WEB-INF/lib. I read that placing postgresql-jdbc.jar into WEB-INF/lib may cause memory leaks.
P.S. I also read, that Hibernate should automaticaly close connections when session commits or rollback and I don't need to close connections explicitly.
Thanks for your suggestions, cos I always need someone who keep my eyes open.

Related

Play framework 2.6.x integrating with hibernate orm 4.3.1 mapping error

I am trying to integrate my java play application with hibernate orm and here is my project structure.
As you can see, I have placed my pojos inside a package named models and hibernate.cfg.xml inside conf.
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/db_name</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>
<mapping resource="models/Coating.hbm.xml"/>
<mapping resource="models/Fitting.hbm.xml"/>
<mapping resource="models/Product.hbm.xml"/>
<mapping resource="models/ProductHasCoating.hbm.xml"/>
<mapping resource="models/ProductHasFitting.hbm.xml"/>
<mapping resource="models/ProductHasSize.hbm.xml"/>
<mapping resource="models/Size.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HibernateUtil class : (inside services)
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Controller Class
public class LoginController extends Controller {
public Result login() throws SQLException {
Session s = HibernateUtil.getSessionFactory().openSession();
Criteria c = s.createCriteria(Coating.class);
c.add(Restrictions.eq("code", "CO3444"));
Coating co = (Coating) c.uniqueResult();
String title = co.getTitle();
s.close();
return ok(views.html.login_page.login.render(title));
}
}
Everything seems fine for me and once I compile and run the application, It terminates the application server with below error.
Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource models/Coating.hbm.xml
Uncaught error from thread [play-dev-mode-akka.actor.default-dispatcher-4]: null, shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled for for ActorSystem[play-dev-mode]
java.lang.ExceptionInInitializerError
at services.HibernateUtil.<clinit>(HibernateUtil.java:18)
at controllers.LoginController.login(LoginController.java:15)
at router.Routes$$anonfun$routes$1.$anonfun$applyOrElse$2(Routes.scala:164)
at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:134)
at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:133)
at play.core.routing.HandlerInvokerFactory$JavaActionInvokerFactory$$anon$8$$anon$2$$anon$1.invocation(HandlerInvoker.scala:108)
at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:82)
at play.http.DefaultActionCreator$1.call(DefaultActionCreator.java:31)
at play.core.j.JavaAction.$anonfun$apply$8(JavaAction.scala:132)
at scala.concurrent.Future$.$anonfun$apply$1(Future.scala:653)
at scala.util.Success.$anonfun$map$1(Try.scala:251)
at scala.util.Success.map(Try.scala:209)
at scala.concurrent.Future.$anonfun$map$1(Future.scala:287)
at scala.concurrent.impl.Promise.liftedTree1$1(Promise.scala:29)
at scala.concurrent.impl.Promise.$anonfun$transform$1(Promise.scala:29)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
at play.core.j.HttpExecutionContext$$anon$2.run(HttpExecutionContext.scala:56)
at play.api.libs.streams.Execution$trampoline$.execute(Execution.scala:70)
at play.core.j.HttpExecutionContext.execute(HttpExecutionContext.scala:48)
at scala.concurrent.impl.CallbackRunnable.executeWithValue(Promise.scala:68)
at scala.concurrent.impl.Promise$KeptPromise$Kept.onComplete(Promise.scala:368)
at scala.concurrent.impl.Promise$KeptPromise$Kept.onComplete$(Promise.scala:367)
at scala.concurrent.impl.Promise$KeptPromise$Successful.onComplete(Promise.scala:375)
at scala.concurrent.impl.Promise.transform(Promise.scala:29)
at scala.concurrent.impl.Promise.transform$(Promise.scala:27)
at scala.concurrent.impl.Promise$KeptPromise$Successful.transform(Promise.scala:375)
at scala.concurrent.Future.map(Future.scala:287)
at scala.concurrent.Future.map$(Future.scala:287)
at scala.concurrent.impl.Promise$KeptPromise$Successful.map(Promise.scala:375)
at scala.concurrent.Future$.apply(Future.scala:653)
at play.core.j.JavaAction.apply(JavaAction.scala:132)
at play.api.mvc.Action.$anonfun$apply$2(Action.scala:96)
at play.api.libs.streams.StrictAccumulator.$anonfun$mapFuture$4(Accumulator.scala:174)
at scala.util.Try$.apply(Try.scala:209)
at play.api.libs.streams.StrictAccumulator.$anonfun$mapFuture$3(Accumulator.scala:174)
at scala.Function1.$anonfun$andThen$1(Function1.scala:52)
at scala.Function1.$anonfun$andThen$1(Function1.scala:52)
at play.api.libs.streams.StrictAccumulator$$anon$1.apply(Accumulator.scala:218)
at play.api.libs.streams.StrictAccumulator$$anon$1.apply(Accumulator.scala:217)
at java.util.function.Function.lambda$andThen$1(Function.java:88)
at java.util.function.Function.lambda$andThen$1(Function.java:88)
at play.libs.streams.Accumulator$StrictAccumulator$1.apply(Accumulator.java:403)
at play.libs.streams.Accumulator$StrictAccumulator$1.apply(Accumulator.java:400)
at scala.Function1.$anonfun$andThen$1(Function1.scala:52)
at scala.Function1.$anonfun$andThen$1(Function1.scala:52)
at scala.Function1.$anonfun$andThen$1(Function1.scala:52)
at play.api.libs.streams.StrictAccumulator.run(Accumulator.scala:207)
at play.core.server.AkkaHttpServer.executeAction(AkkaHttpServer.scala:298)
at play.core.server.AkkaHttpServer.executeHandler(AkkaHttpServer.scala:255)
at play.core.server.AkkaHttpServer.handleRequest(AkkaHttpServer.scala:201)
at play.core.server.AkkaHttpServer.$anonfun$createServerBinding$1(AkkaHttpServer.scala:107)
at akka.stream.impl.fusing.MapAsync$$anon$24.onPush(Ops.scala:1191)
at akka.stream.impl.fusing.GraphInterpreter.processPush(GraphInterpreter.scala:512)
at akka.stream.impl.fusing.GraphInterpreter.processEvent(GraphInterpreter.scala:475)
at akka.stream.impl.fusing.GraphInterpreter.execute(GraphInterpreter.scala:371)
at akka.stream.impl.fusing.GraphInterpreterShell.runBatch(ActorGraphInterpreter.scala:584)
at akka.stream.impl.fusing.GraphInterpreterShell$AsyncInput.execute(ActorGraphInterpreter.scala:468)
at akka.stream.impl.fusing.GraphInterpreterShell.processEvent(ActorGraphInterpreter.scala:559)
at akka.stream.impl.fusing.ActorGraphInterpreter.akka$stream$impl$fusing$ActorGraphInterpreter$$processEvent(ActorGraphInterpreter.scala:741)
at akka.stream.impl.fusing.ActorGraphInterpreter$$anonfun$receive$1.applyOrElse(ActorGraphInterpreter.scala:756)
at akka.actor.Actor.aroundReceive(Actor.scala:517)
at akka.actor.Actor.aroundReceive$(Actor.scala:515)
at akka.stream.impl.fusing.ActorGraphInterpreter.aroundReceive(ActorGraphInterpreter.scala:666)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:527)
at akka.actor.ActorCell.invoke(ActorCell.scala:496)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:257)
at akka.dispatch.Mailbox.run(Mailbox.scala:224)
at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource models/Coating.hbm.xml
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3764)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXmlQueue(Configuration.java:3753)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3741)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at services.HibernateUtil.<clinit>(HibernateUtil.java:14)
... 71 more
Caused by: org.hibernate.MappingException: class models.Coating not found while looking for property: id
at org.hibernate.internal.util.ReflectHelper.reflectedPropertyClass(ReflectHelper.java:233)
at org.hibernate.mapping.SimpleValue.setTypeUsingReflection(SimpleValue.java:362)
at org.hibernate.cfg.HbmBinder.bindSimpleId(HbmBinder.java:453)
at org.hibernate.cfg.HbmBinder.bindRootPersistentClassCommonValues(HbmBinder.java:386)
at org.hibernate.cfg.HbmBinder.bindRootClass(HbmBinder.java:326)
at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:177)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3761)
... 77 more
Caused by: java.lang.ClassNotFoundException: models.Coating
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at org.hibernate.internal.util.ReflectHelper.classForName(ReflectHelper.java:193)
at org.hibernate.internal.util.ReflectHelper.reflectedPropertyClass(ReflectHelper.java:229)
... 83 more
UPDATED
But once I remove all the mappings from hibernate.cfg.xml and change the LoginController code to below :
Session s = HibernateUtil.getSessionFactory().openSession();
Connection c = s.getSessionFactory().getSessionFactoryOptions().getServiceRegistry()
.getService(ConnectionProvider.class).getConnection();
//Criteria c = s.createCriteria(Coating.class);
//c.add(Restrictions.eq("code", "CO3444"));
//Coating co = (Coating) c.uniqueResult();
//String title = co.getTitle();
//s.close();
String title = c.getMetaData().getDatabaseProductName();
return ok(views.html.login_page.login.render(title));
Application starts and runs fine in the browser with the output of MySQL
Which means there is no any hibernate configuration errors and no any errors with the HibernateUtil class either.
Any help would be appreciable. Thank you.
In this case play-framework does not look for the xml mappings inside model package. So I have to put them inside conf package together with hibernate.cfg.xml. Below image shows how the project structure looks like:
And then do not forget to add
Thread.currentThread().setContextClassLoader(OneOfYourModelClass.class.getClassLoader());
line inside the HibernateUtil class before building the session factory.
...
static {
try {
Thread.currentThread().setContextClassLoader(SomeClass.class.getClassLoader());
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
...
so the context can be set ClassLoader of one Entity and the others are also loaded properly.

Cant connect to postgreSQL with Hibernate(Eclipse)

What i do wrong? After running main class i have view in console like in current screenshot below and the console continues to work and nothing happens.
hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/Gillie_PL</property>
<property name="connection.username">postgres</property>
<property name="connection.password">postgres</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
hibernateUtil.class:
package hibernateConn;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory = null;
static {
Configuration cfg =
new Configuration().configure("/hibernateConn/hibernate.cfg.xml");
StandardServiceRegistryBuilder builder =
new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties());
sessionFactory = cfg.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
Main.Class:
package hibernateConn;
import org.hibernate.SessionFactory;
public class Main {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
}
}
After I run Main.class I have in console:
And that's all. Nothing more, the program continues to work and nothing happens, as if recursion occurs ... Maybe I did not correctly specify the settings in xml?
 
I rewrote the HibernateUtil.class :
static {
try{
sessionFactory = new Configuration().configure("/hibernateConn/hibernate.cfg.xml").buildSessionFactory();
}catch(Throwable ex){
System.err.println("++++Initial SessionFactory creation failed.++++: " + ex);
ex.printStackTrace();
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
and it all worked. The question can be closed.

Hibernate can not save object

I am doing the introductory tutorial on Hibernate from PluralSight.
For my database, I am using MYSQL.
In my main method, I am creating an object and I am trying to save it.
However, I get the following error:
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.simpleprogrammer.User
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1447)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:678)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:670)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:665)
at com.simpleprogrammer.Program.main(Program.java:16)
My main method is:
public static void main(String[] args) {
System.out.println("Hello World!");
Session session = HibernateUtilities.getSessionFactory().openSession();
session.beginTransaction();
User user = new User();
user.setName("Joe");
user.setGoal(250);
session.save(user);
session.getTransaction().commit();
session.close();
HibernateUtilities.getSessionFactory().close();
}
The error appears on the line with session.save(user);
My Utilities class:
package com.simpleprogrammer;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtilities {
private static SessionFactory sessionFactory;
private static StandardServiceRegistryBuilder ssrb;
static
{
try
{
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(ssrb.build());
}
catch(HibernateException exception)
{
System.out.println("Problem creating session factory");
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
My hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">appuser</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3307</property>
<property name="hibernate.connection.username">appuser</property>
<property name="hibernate.default_schema">protein_tracker</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="com/simpleprogrammer/User.hbm.xml"/>
</session-factory
</hibernate-configuration>
I am sorry to post all this code, but I'm not sure which part is relevant.
I suspect that my error is caused by the database connection, but I'm not sure how to check that.
I had a syntactic error on the line:
</session-factory
This was in hibernate.cfg.xml
This is my first contribution to stackoverflow.com. And I was facing similar error,but now I resolved it by this given solution. So, I am writing this Answer.
You have to change your utility file like this:
static
{
try
{
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
//ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory();
}
catch(HibernateException exception)
{
System.out.println("Problem creating session factory");
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
ssrb variable declaration and definition must be removed.
put configuration.buildSessionFactory(); instead of configuration.buildSessionFactory(ssrb.build());

How does getCurrentSession work without openSession?

This is my code:
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/sakila</property>
<property name="connection.username">root</property>
<property name="connection.password"/>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.show_sql">false</property>
<mapping class="biz.tugay.saqila.model.Actor" />
</session-factory>
</hibernate-configuration>
HibernateUtil.java
package biz.tugay.saqila.dao;
/* User: koray#tugay.biz Date: 06/08/15 Time: 18:29 */
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory SESSION_FACTORY;
public static void buildSessionFactory() {
if (SESSION_FACTORY != null) {
return;
}
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
SESSION_FACTORY = configuration.buildSessionFactory(serviceRegistry);
}
public static Session getCurrentSession() {
return SESSION_FACTORY.getCurrentSession();
}
public static void killSessionFactory() {
if (SESSION_FACTORY != null) {
SESSION_FACTORY.close();
}
}
}
and a sample DAO class:
package biz.tugay.saqila.dao;
/* User: koray#tugay.biz Date: 06/08/15 Time: 18:37 */
import biz.tugay.saqila.model.Actor;
import org.hibernate.Session;
import java.util.List;
#SuppressWarnings("unchecked")
public class ActorDao {
public List<Actor> getAllActors() {
Session session = HibernateUtil.getCurrentSession();
session.beginTransaction();
List<Actor> actors = session.createQuery("FROM Actor").list();
session.close();
return actors;
}
public Actor getWithId(int id) {
Session session = HibernateUtil.getCurrentSession();
session.beginTransaction();
Actor actor = (Actor) session.get(Actor.class, id);
session.close();
return actor;
}
}
Well as you can see I am not calling openSession anywhere, just getCurrentSession. But how does this work?
Also, is this the right way to do things or am I just lucky that this works?
Btw I also have this listener:
package biz.tugay.saqila.servlet;
/* User: koray#tugay.biz Date: 06/08/15 Time: 19:00 */
import biz.tugay.saqila.dao.HibernateUtil;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
#WebListener
public class HibernateConfigurator implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
HibernateUtil.buildSessionFactory();
}
#Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("Killing Session Factory.");
HibernateUtil.killSessionFactory();
}
}
If you set hibernate.current_session_context_class to thread, then you can access that session anywhere in application by using the SessionFactory.getCurrentSession().
if you don't want the session to be bound to context then use OpenSession . In some scenario you may need a different session - other than one bound to the context in that case you can use OpenSession instead of currentSession.
SessionFactory.openSession() always opens a new session that you have to close once you are done with the DB operations. SessionFactory.getCurrentSession() returns a session bound to a context and you don't need to close this.
You should never use one session per application - session is not a thread safe object,Which cannot be shared by multiple threads.Always use one session per transaction
The javadoc says:
Obtains the current session. The definition of what exactly "current" means controlled by the CurrentSessionContext impl configured for use.
You're using a ThreadLocalSessionContext. Its javadoc says:
A CurrentSessionContext impl which scopes the notion of current session by the current thread of execution. [...] In the interest of usability, it was decided to have this default impl actually generate a session upon first request and then clean it up after the Transaction associated with that session is committed/rolled-back.
You shouldn't close sessions obtained that way. Instead, you should commit the transaction that you have begun. This will close the session, as the documentation says.

hibernate.cfg.xml not found (eclipse)

I started using Hibernate today and tested a simple example but I'm getting the error: hibernate.cfg.xml not found.
I putted the hibernate.cfg.xml file in the src folder and here is its content:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">test</property>
<property name="connection.password">test</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/mycompany/model/Product.hbm.xml"/>
</session-factory>
</hibernate-configuration>
And I putted the HibernateUtil.java file under util folder (src/util) and here is its content
package util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure("hibernate.cgf.xml").buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
I also have the Jars added to the build path.
My class Test.java :
import ...
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ProductDao pd = new ProductDao();
try {
Product p = new Product("PC", 1000L);
pd.add(p);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The add method :
public void add(Product p) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.beginTransaction();
session.save(p);
tx.commit();
}
Thanks in advance
If using maven try putting it in
/src/main/resources
If using simple eclipse project (without maven), put it in project root directory (not in the src)
Also you misspelled the name of the file in the source
return new Configuration().configure("hibernate.cgf.xml").buildSessionFactory();
it must be
hibernate.cfg.xml
If its a Maven project just add cfg.xml file in /src/main/resources in eclips

Categories

Resources