Broken pipe with PostgreSQL - java

First of all, I already read posts relating to this error prior to posting this question. However, most of them are not using PostgreSQL, so this error might be handled differently. Here's the stack trace of this error:
WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 08006
4450102501 [XmlBlaster.socket_ssl.cbWorkerThread] ERROR org.hibernate.util.JDBCExceptionReporter - An I/O error occured while sending to the backend.
java.lang.RuntimeException: org.hibernate.exception.JDBCConnectionException: could not execute query using iterate
at edu.umd.cattlab.vatraffic.listener.output.VaTrafficDbModule.processSingleMessage(VaTrafficDbModule.java:380)
at edu.umd.cattlab.vatraffic.listener.output.VaTrafficDbModule.processMessage(VaTrafficDbModule.java:266)
at edu.umd.cattlab.vatraffic.listener.input.InputModule.sendMessageToOuputModules(InputModule.java:36)
at edu.umd.cattlab.vatraffic.listener.input.XmlBlaster.update(XmlBlaster.java:173)
at org.xmlBlaster.client.XmlBlasterAccess.update(XmlBlasterAccess.java:1043)
at org.xmlBlaster.client.protocol.AbstractCallbackExtended.update(AbstractCallbackExtended.java:111)
at org.xmlBlaster.client.protocol.AbstractCallbackExtended.update(AbstractCallbackExtended.java:199)
at org.xmlBlaster.util.protocol.RequestReplyExecutor.receiveReply(RequestReplyExecutor.java:444)
at org.xmlBlaster.client.protocol.socket.WorkerThread.run(WorkerThread.java:51)
Caused by: org.hibernate.exception.JDBCConnectionException: could not execute query using iterate
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.hql.QueryLoader.iterate(QueryLoader.java:427)
at org.hibernate.hql.ast.QueryTranslatorImpl.iterate(QueryTranslatorImpl.java:380)
at org.hibernate.engine.query.HQLQueryPlan.performIterate(HQLQueryPlan.java:224)
at org.hibernate.impl.SessionImpl.iterate(SessionImpl.java:1192)
at org.hibernate.impl.QueryImpl.iterate(QueryImpl.java:46)
at edu.umd.cattlab.schema.hibernate.cattXML.extensions.VaTraffic.VaTrafficHelper.laneMap(VaTrafficHelper.java:165)
at edu.umd.cattlab.vatraffic.listener.output.VaTrafficDbModule.processIncidentDescription(VaTrafficDbModule.java:396)
at edu.umd.cattlab.vatraffic.listener.output.VaTrafficDbModule.processSingleMessage(VaTrafficDbModule.java:360)
... 8 more
Caused by: org.postgresql.util.PSQLException: An I/O error occured while sending to the backend.
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:218)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:451)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:350)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:254)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1787)
at org.hibernate.loader.hql.QueryLoader.iterate(QueryLoader.java:404)
... 15 more
Caused by: java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.write(Unknown Source)
at org.postgresql.core.PGStream.SendChar(PGStream.java:174)
at org.postgresql.core.v3.QueryExecutorImpl.sendBind(QueryExecutorImpl.java:829)
at org.postgresql.core.v3.QueryExecutorImpl.sendOneQuery(QueryExecutorImpl.java:1053)
at org.postgresql.core.v3.QueryExecutorImpl.sendQueryPreamble(QueryExecutorImpl.java:373)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:189)
Our application uses Hibernate, so here's the Hibernate configuration:
<?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">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://cannottell.umd.edu</property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Enable C3P0 database connection pool -->
<!----> <!--<property name="c3p0.min_size">2</property>
<property name="c3p0.max_size">5</property>
<property name="c3p0.timeout">600</property>
<property name="c3p0.max_statements">0</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.acquire_increment">1</property>-->
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Oracle doesn't handle prepared statement caching very well. This disables prepared statements. -->
<property name="statement_cache.size">0</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.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">false</property>
<!-- ritis schema mappings -->
<mapping resource="edu/umd/cattlab/schema/hibernate/cattXML/cattXML.hbm.xml"/>
<mapping resource="edu/umd/cattlab/schema/hibernate/cattXML/cattXMLLookup.hbm.xml"/>
<!-- vatraffic schema mappings -->
<mapping resource="edu/umd/cattlab/schema/hibernate/cattXML/extensions/VaTraffic/vaTraffic.hbm.xml"/>
<mapping resource="edu/umd/cattlab/schema/hibernate/cattXML/extensions/VaTraffic/vaTrafficLookup.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Here's my questions:
Is this error really comes from the lost connection to the database, or is it an error from my code? (If the latter is true, then I'll provide the codes involved)
Either way, how should I deal with this error?
If the error comes from the database, how can I replicate this error (for testing purpose), provided that I do not have direct access to the database?
I'm sorry if I'm asking too many questions.By the way, I would love to add more information regarding to this question if necessary. I really appreciate any response from you all. Thank you.
ADDED
Here's the code for opening and closing the hibernate session:
Session sess = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
String eventId = null;
try {
sess.getTransaction().setTimeout(new Integer(configuration
.getProperty("messageProcessingTimeout")));
if (!sess.isConnected()) {
attemptReconnect();
} else {
log.debug("Database connection open.");
}
//tx = sess.beginTransaction();
//log.debug("After transaction");
eventId = processIncidentDescription(message, sess);
//tx.commit();
// Sending jmsNotify.
if (Boolean.valueOf(configuration.getProperty("sendJmsNotify"))
&& eventId != null) {
log.debug("Sending jmsNotify message " + "<notify id=\""
+ eventId + "\"/>");
jmsSender.sendMessage("<notify id=\"" + eventId + "\"/>");
}
} catch (Exception e) {
try {
if (tx != null)
tx.rollback();
} catch (TransactionException te) {
log.warn("Unable to roll back transaction.");
}
throw new RuntimeException(e);
} finally {
sess.close();
}
ADDED
Here's the code that might cause the error:
public static HashMap<String,HashMap<String,Object>> laneMap(Session sess){
HashMap<String,HashMap<String,Object>> table = new HashMap<String,HashMap<String,Object>>();
Query query = sess.createQuery("from Direction");
Iterator<Object> iterate = query.iterate();
while (iterate.hasNext()){
Object obj = iterate.next();
Direction direct = (Direction) obj;
if (table.get("direction") == null){
table.put("direction", new HashMap<String,Object>());
}
String directDesc = direct.getDirectionDescription();
table.get("direction").put(directDesc, direct);
}
Query query2 = sess.createQuery("from LaneStatus");
Iterator<Object> iterate2 = query2.iterate();
while (iterate2.hasNext()){
Object obj = iterate2.next();
LaneStatus laneStatus = (LaneStatus) obj;
if (table.get("lane_status") == null){
table.put("lane_status", new HashMap<String,Object>());
}
String directDesc = laneStatus.getLaneStatusDescription();
table.get("lane_status").put(directDesc, laneStatus);
}
Query query3 = sess.createQuery("from LaneType");
Iterator<Object> iterate3 = query3.iterate();
while (iterate3.hasNext()){
Object obj = iterate3.next();
LaneType laneType = (LaneType) obj;
if (table.get("lane_type") == null){
table.put("lane_type", new HashMap<String,Object>());
}
String directDesc = laneType.getLaneTypeDescription();
table.get("lane_type").put(directDesc, laneType);
}
return table;
}

This issue happens when your application can no longer connect to the Postgres DB. I've had it happen when I've been VPN'ed in to my office, and then close the VPN connection, which severs the DB connection. My local server will then show the above. If this issue is happening in your server environment, you need to see if there are network connectivity issues.

Could it be the case that your app tries to open more connections to PostgreSQL simultaneously than configured in you PG instance allowed as max concurrent connections?

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.

Exception in thread "main" java.lang.IllegalStateException: Session/EntityManager is closed

I want to run this very basic Hibernate code:
public static void main(String[] args) throws Exception
{
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session session = sessFact.getCurrentSession();
Transaction tr = session.beginTransaction();
SystemUsers myContact = new SystemUsers(3);
SystemUsers yourContact = new SystemUsers(4);
SystemUsers yourContsact = new SystemUsers(5);
SystemUsers yourContssssact = new SystemUsers(6);
SystemUsers yourContssssasssct = new SystemUsers(7);
// Saving to the database
session.save(myContact);
session.save(yourContact);
session.save(yourContsact);
session.save(yourContssssact);
session.save(yourContssssasssct);
session.flush();
tr.commit();
List<SystemUsers> contactList = session.createQuery("from SYSTEM_USERS").list();
for (SystemUsers contact : contactList)
{
System.out.println("Id: " + contact.getId());
}
System.out.println("Successfully inserted");
sessFact.close();
}
config file:
<hibernate-configuration>
<session-factory>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.connection.url">jdbc:sqlite:/C:/sqlite/test.sqlite</property>
<property name="hibernate.connection.username"></property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.release_mode">auto</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.connection.autoReconnect">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.web.models.SystemUsers"/>
</session-factory>
</hibernate-configuration>
I get error:
Exception in thread "main" java.lang.IllegalStateException: Session/EntityManager is closed
at org.hibernate.internal.AbstractSharedSessionContract.checkOpen(AbstractSharedSessionContract.java:337)
at org.hibernate.engine.spi.SharedSessionContractImplementor.checkOpen(SharedSessionContractImplementor.java:135)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:648)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:102)
I use latest Hibernate version. Can you give me some advice how I can fix this issue?
Probably I need to initialize different factory?
i think the problem is in
session.flush();//this will flush all the data in the session so for commmiting there wont be any data.
tr.commit();
try this.
tr.commit();
session.flush();

Could not parse configuration: hibernate.cfg.xml caused by org.dom4j.DocumentException: Error on line 2 of document

I am not so into Hibernate and I have the following problem trying to follow a tutorial. I am using Hibernate 4
So I have a client class named HelloWorldClient:
public class HelloWorldClient {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Message message = new Message( "Hello World with Hibernate & JPA Annotations" );
session.save(message);
session.getTransaction().commit();
session.close();
}
}
As you can see this class use the HibernateUtil to retrieve the Hibernate Session object, this one:
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
return configuration.buildSessionFactory( new StandardServiceRegistryBuilder().applySettings( configuration.getProperties() ).build() );
}
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;
}
}
and, as you can see, this class use the hibernate.cfg.xml configuration file that is putted into the root of my project, this one:
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hello-world</property>
<property name="connection.username">root</property>
<property name="connection.password">myPswd</property>
<!--SQL dialect -->
<property name = dialect ">org.hibernate.dialect.MySQLDialect</property>
<!--Use Annotation - based mapping metadata -->
<mapping class="entity.Message" />
</session-factory>
</hibernate-configuration>
The problem is that when I perform this application I obtain this error message:
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
Initial SessionFactory creation failed.org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
Exception in thread "main" java.lang.ExceptionInInitializerError
at util.HibernateUtil.buildSessionFactory(HibernateUtil.java:21)
at util.HibernateUtil.<clinit>(HibernateUtil.java:10)
at client.HelloWorldClient.main(HelloWorldClient.java:13)
Caused by: org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2165)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2077)
at util.HibernateUtil.buildSessionFactory(HibernateUtil.java:15)
... 2 more
Caused by: org.dom4j.DocumentException: Error on line 2 of document : Non è consentita una destinazione di istruzione di elaborazione corrispondente a "[xX][mM][lL]". Nested exception: Non è consentita una destinazione di istruzione di elaborazione corrispondente a "[xX][mM][lL]".
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2157)
... 4 more
It seems that it can't read the hibernate.cfg.xml file or something like this.
Why? What am I missing ? How can I fix this issue ?
The mapping document is not a valid XML. Fix the line 19:
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
Other then that it shoud work.
There are 2 problems in your mapping file :
white line is not allowed on line 2: just remove the empty line. (this is the cause of your current error... very explicit by the way : "Error on line 2 of document")
quote is missing when you declare the dialect:
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

Hibernate query.executeUpdate() not working properly

Hibernate query.executeUpdate() is not working..
Here is the code for updating
public static void expDue(){
Session session=HibernateUtil.getSessionFactory().openSession();
java.util.Date utilDate=new java.util.Date();
java.sql.Date sqldate=new java.sql.Date(utilDate.getTime());
Format formatter = new SimpleDateFormat("yyyy-MM-dd");
String a= formatter.format(sqldate);
boolean b=false;
if(b==false){
Query query = session.createQuery(" update Issue set dueStatus = 'true' where returnDate='"+a+"'");
int result = query.executeUpdate();
System.out.println(query.executeUpdate()+"Rows affected: " + result);
b=true;
}
Here, printing the result shows correct value, but no change in database.
And hibernate code
<hibernate-configuration>
<session-factory>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="hibernate.connection.url">jdbc:hsqldb:db/hsql/library;shutdown=true</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">sa</property>
<property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- JDBC connection pool (use the built-in one) -->
<property name="connection.pool_size">1</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.NoCacheProvider</property>
<!-- disable batching so HSQLDB will propagate errors correctly. -->
<property name="jdbc.batch_size">0</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- List all the mapping documents we're using -->
<mapping class="com.habitz.librarymanagement.domain.Admin" />
<mapping class="com.librarymanagement.domain.Book" />
<mapping class="com.librarymanagement.domain.Category" />
<mapping class="com.librarymanagement.domain.Group" />
<mapping class="com.librarymanagement.domain.Issue" />
<mapping class="com.librarymanagement.domain.Member" />
</session-factory>
</hibernate-configuration>
In console printing the result shows correct values. But the database shows no change...
If you know about this please share answers here...
UPDATE
Transaction tx = null;
tx = session.beginTransaction();
Query query = session
.createQuery(" update Issue set dueStatus = 'true' where returnDate='"
+ a + "'");
int result = query.executeUpdate();
System.out.println(query.executeUpdate() + "Rows affected: "
+ result);
tx.commit();
Transaction tx = null;
tx = session.beginTransaction();
boolean b = false;
if (b == false) {
Query query = session
.createQuery(" update Issue set dueStatus = 'true' where returnDate='"
+ a + "'");
query.executeUpdate();
tx.commit();
You have forgotten to execute update before committing transaction.

Hibernate throws strange error: Class is not mapped

this is the error
org.hibernate.hql.ast.QuerySyntaxException: Payment is not mapped [select p from Payment p]
I don't understand how come this error is thrown, the class should be mapped as I will show you briefly. I have a very basic config, like this one: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/ch01.html
I have tried to add the mapping definition into hibernate.cfg.xml and I have also tried to add it programmatically. Neither of them worked. Could anybody tell me what am I missing here? (it is not the first time I put together a Hibernate project)
this is the 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="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/paymentsdatabase</property>
<property name="hibernate.connection.username">xxx</property>
<property name="hibernate.connection.password">xxx</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- <mapping class="com.lsyh.swati.zk.model.Payment"/> -->
</session-factory>
</hibernate-configuration>
the database connection is working fine, I have tested that
this is the static initializer in my HibernateUtil
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration()
.addPackage("com.lsyh.swati.zk.model")
.addAnnotatedClass(Payment.class)
.configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed. " + ex);
throw new ExceptionInInitializerError(ex);
}
}
and this is where I use the sessionFactory in the PaymentIODb class:
public static List<Payment> readDataFromDb(){
StatelessSession session = StoreHibernateUtil.getSessionFactory().openStatelessSession();
Query query = session.createQuery("select p from Payment p");
List<Payment> payments = query.list();
session.close();
return payments;
}
this is the stack trace
org.hibernate.hql.ast.QuerySyntaxException: Payment is not mapped [select p from Payment p]
at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:158)
at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:87)
at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:70)
at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:255)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3056)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:2945)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:688)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:544)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:228)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:160)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
at com.lsyh.swati.zk.controller.PaymentIODb.readDataFromDb(PaymentIODb.java:35)
at com.lsyh.swati.zk.controller.PaymentIODb.resolveVariable(PaymentIODb.java:20
I'd expect one of two things to be the reason:
either you don't have Payment listed in your hibernat.cfg.xml or where ever you config your mapped classes.
another reason might be the confusion between javax...Entity and org.hibernate....Entity. Make sure you use the first one.
Instead of
Query query = session.createQuery("select p from Payment p");
try this
Query query = session.createQuery("select p from " + Payment.class.getName() + " p");
uncomment the commented mapping code in hibernate.cfg.xml config file
<!-- <mapping class="com.lsyh.swati.zk.model.Payment"/> -->
change it to
<mapping class="com.lsyh.swati.zk.model.Payment"/>
for more information refer this link
http://www.javabeat.net/tips/112-configure-mysql-database-with-hibernate-mappi.html
Your entity bean is not getting registered i guess.
Set proper root package name of your entity beans in packagesToScan property.
Also check your #Table(name="name_of_your_table").
Although accepted answer is correct, would like to add context to the first part of the answer.
Inside of your config.java (or whatever you have named your application configuration file in packages), ensure you have properly configured your entityScan:
package com.example.config;
import org.springframework.boot.autoconfigure.domain.EntityScan;
#EntityScan("com.example.entities")
However, if you like our team have moved your objects into their own packages, you may want to allow for a scan of all package folders:
#EntityScan("com.example.*")
Now that not all entities are in the entities folder specifically.
For me, my Class was not listed in my Persistence.xml file in the class section.
Do that to solve the ish. or wherever your classes are listed.
I had same problem , instead #Entityt mapping i
I used following code for getting records
private #Autowired HibernateTemplate incidentHibernateTemplate;
List<Map<String, Object>> list = null;
list = incidentHibernateTemplate.execute(new HibernateCallback<List<Map<String, Object>>>() {
#Override
public List<Map<String, Object>> doInHibernate(Session session) throws HibernateException {
Query query = session.createSQLQuery("SELECT * from table where appcode = :app");
query.setParameter("app", apptype);
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
return query.list();
}
});
I used following code for update
private #Autowired HibernateTemplate incidentHibernateTemplate;
Integer updateCount = 0;
updateCount = incidentHibernateTemplate.execute((Session session) -> {
Query<?> query = session
.createSQLQuery("UPDATE tablename SET key = :apiurl, data_mode = :mode WHERE apiname= :api ");
query.setParameter("apiurl", url);
query.setParameter("api", api);
query.setParameter("mode", mode);
return query.executeUpdate();
}
);

Categories

Resources