-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 8 posts ] 
Author Message
 Post subject: What's wrong with my Hibernate Utility class ?
PostPosted: Sat Dec 30, 2017 8:07 am 
Beginner
Beginner

Joined: Tue Aug 08, 2017 12:14 am
Posts: 44
Hi experts,

I got the below error and I suspected there is an error some where but I could not figure out why.

Initially, I got error in accessing tables metadata then I saw this Utility class as per

https://stackoverflow.com/questions/436 ... 6#43718626

and I copied it and the metadata error is gone but then the new error is :

Quote:
java.lang.NullPointerException
at util.HibernateUtil.getSession(HibernateUtil.java:40)
at Business.RegisterService.register(RegisterService.java:16)


Here's the class :

Code:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;



public class HibernateUtil {
   
   private static StandardServiceRegistry registry;
     private static SessionFactory sessionFactory;

      public static SessionFactory getSessionFactory() {
           return buildSessionFactory();
      }

     public static SessionFactory buildSessionFactory() {
       if (sessionFactory == null) {
         try {
           registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
           MetadataSources sources = new MetadataSources(registry);
           Metadata metadata = sources.getMetadataBuilder().build();
           sessionFactory = metadata.getSessionFactoryBuilder().build();
         } catch (Exception e) {
           e.printStackTrace();
           shutdown();
         }
       }
       return sessionFactory;
     }

   public static Session getSession() {
           Session hibernateSession = getSessionFactory().getCurrentSession();
           return hibernateSession;
         }

     public static void shutdown() {
       if (registry != null) {
         StandardServiceRegistryBuilder.destroy(registry);
       }
     }
   }


[code]
public class RegisterService {

   public boolean register(Tutor tutor){
   Session session = HibernateUtil.getSession(); // error here line 16
   if(isTutorExists(tutor)) return false;
   
   Transaction tx = null;
   try{
      tx = session.getTransaction();


<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>

I really can't figure out what is wrong. Hope someone can let me know the reason.

Tks.


Top
 Profile  
 
 Post subject: Re: What's wrong with my Hibernate Utility class ?
PostPosted: Sat Dec 30, 2017 10:32 am 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1630
Location: Romania
First, you don't need a BibernateUtil class. Just use Spring or Java EE and inject the SessionFactory or the EntityManager Factory.

Second, the getSessionFactory method is wrong, it should be like this:

Code:
public static synchronized SessionFactory getSessionFactory() {
    return sessionFactory != null ?
        sessionFactory :
        buildSessionFactory();
}


If you already have a SessionFactory, just reuse it and make sure that only one Thread can build a SessionFactory.


Top
 Profile  
 
 Post subject: Re: What's wrong with my Hibernate Utility class ?
PostPosted: Sun Dec 31, 2017 10:45 am 
Beginner
Beginner

Joined: Tue Aug 08, 2017 12:14 am
Posts: 44
vlad wrote:
First, you don't need a BibernateUtil class. Just use Spring or Java EE and inject the SessionFactory or the EntityManager Factory.

Second, the getSessionFactory method is wrong, it should be like this:

Code:
public static synchronized SessionFactory getSessionFactory() {
    return sessionFactory != null ?
        sessionFactory :
        buildSessionFactory();
}


If you already have a SessionFactory, just reuse it and make sure that only one Thread can build a SessionFactory.


Hi vlad,

After I changed the utility file, I am getting another 'funny' error -
Quote:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hi5s.subject' doesn't exist


But, the table exists in my database.

What do you think I should do in this case ?

Furthermore, I'd like to clarify if Tomcat can work with Java EE SessionFactory bean injection ? - Are you referring to EJB 3 ?


Top
 Profile  
 
 Post subject: Re: What's wrong with my Hibernate Utility class ?
PostPosted: Sun Dec 31, 2017 6:55 pm 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1630
Location: Romania
Quote:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hi5s.subject' doesn't exist


Maybe the catalog hi5s was not set properly in Hibernate.

Quote:
Furthermore, I'd like to clarify if Tomcat can work with Java EE SessionFactory bean injection ? - Are you referring to EJB 3 ?


If you use Spring, then yes. If you don't use Spring, then you need something like TomEE.


Top
 Profile  
 
 Post subject: Re: What's wrong with my Hibernate Utility class ?
PostPosted: Thu Jan 04, 2018 11:32 am 
Beginner
Beginner

Joined: Tue Aug 08, 2017 12:14 am
Posts: 44
vlad wrote:
Quote:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hi5s.subject' doesn't exist


Maybe the catalog hi5s was not set properly in Hibernate.

Quote:
Furthermore, I'd like to clarify if Tomcat can work with Java EE SessionFactory bean injection ? - Are you referring to EJB 3 ?


If you use Spring, then yes. If you don't use Spring, then you need something like TomEE.


Hi vlad,

I think I want to keep things simple before I explore Spring cos you know my Java knowledge still needs improvement. If not for difficult in doing it via the JDBC way for the join table, I would not jump into Hibernate either. Please correct me if I am on the right track being like this.

For now, is it ok just to use SessionFactory from Hibernate to do the session transaction ?

Anyway, I keep getting the below error and I just can't resolve it and so I am here seeking your expertise again:

Code:
Jan 04, 2018 11:23:14 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Jan 04, 2018 11:23:14 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jan 04, 2018 11:23:14 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jan 04, 2018 11:23:14 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL55Dialect
Jan 04, 2018 11:23:21 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@4dfb86db] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Jan 04, 2018 11:23:21 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Jan 04, 2018 11:23:21 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Table 'hi5s.subject' doesn't exist
Jan 04, 2018 11:23:21 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/hi5s?useSSL=false]
Initial SessionFactory creation failed.org.hibernate.exception.SQLGrammarException: Error accessing tables metadata
Jan 04, 2018 11:23:21 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [controller.tutorController] in context with path [/Hi5S] threw exception [Servlet execution threw an exception] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hi5s.subject' doesn't exist
   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
   at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
   at java.lang.reflect.Constructor.newInstance(Unknown Source)
   at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
   at com.mysql.jdbc.Util.getInstance(Util.java:408)
   at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
   at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
   at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
   at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2480)
   at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2438)
   at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1381)
   at com.mysql.jdbc.DatabaseMetaData$2.forEach(DatabaseMetaData.java:2441)
   at com.mysql.jdbc.DatabaseMetaData$2.forEach(DatabaseMetaData.java:2339)
   at com.mysql.jdbc.IterateBlock.doForAll(IterateBlock.java:50)
   at com.mysql.jdbc.DatabaseMetaData.getColumns(DatabaseMetaData.java:2337)
   at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.populateTablesWithColumns(InformationExtractorJdbcDatabaseMetaDataImpl.java:350)
   at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getTables(InformationExtractorJdbcDatabaseMetaDataImpl.java:337)
   at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.getTablesInformation(DatabaseInformationImpl.java:120)
   at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:65)
   at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:203)
   at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:110)
   at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183)
   at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
   at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:309)
   at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)
   at util.HibernateUtil.buildSessionFactory(HibernateUtil.java:27)
   at util.HibernateUtil.<clinit>(HibernateUtil.java:16)
   at Business.RegisterService.register(RegisterService.java:16)
   at controller.tutorController.doPost(tutorController.java:79)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
   at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
   at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
   at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
   at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
   at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
   at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
   at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
   at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
   at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
   at java.lang.Thread.run(Unknown Source)


And here's my hibernate.cfg.xml :

Code:
<session-factory>

      <!-- SQL Dialect -->

      <property name="dialect">org.hibernate.dialect.MySQL55Dialect</property>
      <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hi5s?useSSL=false</property>
      <property name="hibernate.connection.username">root</property>
      <property name="hibernate.connection.password">password</property>

      <property name="transation.factory_class">org.hibernate.transaction.JDBCTransactionFactory</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="hibernate.show_sql">true</property>
      <property name="hibernate.id.new_generator_mappings">false</property>
      <!-- Upate is for table already there -->
      <property name="hibernate.hbm2ddl.auto">update</property>

      <!-- Enable Hibernate's automatic session context management -->
      <property name="hibernate.current_session_context_class">thread</property>

      <!-- Mention here all the model classes along with their package name -->
      <mapping class="model.User" />
      <mapping class="model.Tutor" />
      <mapping class="model.Subject" />
      
      </session-factory>

When you mentioned the catalog hi5s was not set properly in Hibernate. Are you referring to this cfg.xml file ? Cos everything is there.....


Top
 Profile  
 
 Post subject: Re: What's wrong with my Hibernate Utility class ?
PostPosted: Thu Jan 04, 2018 11:49 am 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1630
Location: Romania
If you specified the table like that:

Code:
<class name = "Subject" table = "hi5s.subject">


in the entity mapping, try setting it to:

Code:
<class name = "Subject" table = "subject">


Top
 Profile  
 
 Post subject: Re: What's wrong with my Hibernate Utility class ?
PostPosted: Mon Jan 08, 2018 11:44 am 
Beginner
Beginner

Joined: Tue Aug 08, 2017 12:14 am
Posts: 44
vlad wrote:
First, you don't need a BibernateUtil class. Just use Spring or Java EE and inject the SessionFactory or the EntityManager Factory.

If you already have a SessionFactory, just reuse it and make sure that only one Thread can build a SessionFactory.

Hi vlad,

I'd like to clarify with you regarding your comment - only one Thread can build a SessionFactory.

How do I make sure that it is only one Thread cos I have insert every method in my logic class with a SessionFactory factory = HibernateUtil.getSessionFactory();

Session session = factory.openSession();
follows by beginTransaction...and the standard transaction.rollback follows by session.close().

So, I presume if my controller is to check one method follows by another, the session will open and close(1 thread), open and close( a new thread will start again).

But, it is not working at all. Is there something that I am missing here?


Cos run when I debug my app, I got the following error stack trace and it stays forever at many Daemon threads :
Quote:
Daemon Thread [http-nio-8080-exec-6] (Suspended)
Unsafe.park(boolean, long) line: not available [native method]
LockSupport.park(Object) line: not available
AbstractQueuedSynchronizer$ConditionObject.await() line: not available
TaskQueue(LinkedBlockingQueue<E>).take() line: not available
TaskQueue.take() line: 103
TaskQueue.take() line: 31
ThreadPoolExecutor(ThreadPoolExecutor).getTask() line: not available
ThreadPoolExecutor(ThreadPoolExecutor).runWorker(ThreadPoolExecutor$Worker) line: not available
ThreadPoolExecutor$Worker.run() line: not available
TaskThread$WrappingRunnable.run() line: 61
TaskThread(Thread).run() line: not available


Top
 Profile  
 
 Post subject: Re: What's wrong with my Hibernate Utility class ?
PostPosted: Mon Jan 08, 2018 12:42 pm 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1630
Location: Romania
Quote:
So, I presume if my controller is to check one method follows by another, the session will open and close(1 thread), open and close( a new thread will start again).


No. Just use synchronized for when you create the Sessionfactory, as I already mentioned.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 8 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.