Stuck at this place I am new to hibernate and making a sample code after watching tutorial However I am stuck connecting hibernate with MySql.
Here is hibernate.cfg.xml placed in the source folder
<?xml version='1.0' encoding='utf-8'?>
<!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License:
GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the
lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. -->
<hibernate-configuration
xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-configuration
hibernate-configuration-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<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">root</property>
<property name="connection.password">root</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>
<property name="current_session_context_class">thread</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">create</property>
<mapping class="com.javapapers.UserDetails" />
</session-factory>
</hibernate-configuration>
And here is my HibernateTest.java file
package com.javapapers;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDetails user=new UserDetails();
user.setUserId(1);
user.setUserName("Mannu");
System.out.println("Here");
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
System.out.println("Not even printed");
Session session=sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
Here is UserDetails.java
package com.javapapers;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class UserDetails {
#Id
private int userId;
private String userName;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
And Here is Error Report
Here
Nov 11, 2015 2:23:03 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.2.Final}
Nov 11, 2015 2:23:03 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Nov 11, 2015 2:23:03 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 10 and column 56 in RESOURCE hibernate.cfg.xml. Message: cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
at org.hibernate.cfg.Configuration.configure(Configuration.java:259)
at org.hibernate.cfg.Configuration.configure(Configuration.java:245)
at com.javapapers.HibernateTest.main(HibernateTest.java:15)
Caused by: javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 10; columnNumber: 56; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:420)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:401)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:374)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:126)
... 6 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 10; columnNumber: 56; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1906)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:746)
at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.startElement(ValidatorHandlerImpl.java:570)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(ValidatingUnmarshaller.java:86)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(InterningXmlVisitor.java:60)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.handleStartElement(StAXEventConnector.java:246)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(StAXEventConnector.java:115)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:398)
... 8 more
Create SessionFactory like that. It worked at Hibernate 4.3.
Configuration configuration = new Configuration();
configuration.configure();
private static ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
private static SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
And it's total violation of factory pattern to do that in main. Make separate class for it.
Related
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.
Mapping classes <mapping class="org.hibernate.test.akashtest.UserDetails"/>.
The configuration file is not able to pick the UserDetails class.
Added Annotation Class in configuration, packages location as well.
How can I fix this?
Code:
package org.hibernate.test.akashtest;
import java.lang.annotation.Annotation;
import javax.persistence.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.fasterxml.classmate.AnnotationConfiguration;
import com.fasterxml.classmate.AnnotationInclusion;
public class hibernate_1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDetails user=new UserDetails();
user.setuserId(1);
user.setuserName("First User");
SessionFactory sessionFactory= new Configuration().addAnnotatedClass(org.hibernate.test.akashtest.UserDetails.class).configure("/org/hibernate/test/akashtest/hibernate.cfg.xml").buildSessionFactory();
Session session=sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
/// My hibernate.cfg.xml
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/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://localhost:5432/hibernatedb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">akash5758</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</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">create</property>
<mapping package="org.hibernate.test.akashtest"/>
<mapping class="org.hibernate.test.akashtest.UserDetails"/> /*MAPPING CLASS*/
</session-factory>
</hibernate-configuration>
/// My UserDetails.java
package org.hibernate.test.akashtest;
public class UserDetails {
private int userId;
private String userName;
public int getUserId()
{
return userId;
}
public void setuserId(int userId)
{
this.userId=userId;
}
public String getuserName()
{
return userName;
}
public void setuserName(String userName)
{
this.userName=userName;
}
}
You have to add #Entity annotation in your UserDetails class.
I try to use spring and hibernate to populate a database (MySQL). But after ~ 25-30k inserts, i got the following error :
févr. 15, 2017 12:14:27 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 08001
févr. 15, 2017 12:14:27 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:431)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy28.create(Unknown Source)
at main.Main.recupReq(Main.java:353)
at main.Main.manageCategories(Main.java:140)
at main.Main.transformOldModelToNewModel(Main.java:119)
at main.Main.transferXMLtoDB(Main.java:82)
at main.Main.main(Main.java:59)
Caused by: org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:48)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:102)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:129)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:247)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:254)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:203)
at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:56)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:189)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
... 12 more
Caused by: java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:526)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:513)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:505)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:479)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:489)
at com.mysql.cj.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:1677)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1601)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:633)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:347)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:219)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:196)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:159)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:99)
... 19 more
Caused by: com.mysql.cj.core.exceptions.CJCommunicationsException: The driver was unable to create a connection due to an inability to establish the client portion of a socket.
This is usually caused by a limit on the number of sockets imposed by the operating system. This limit is usually configurable.
For Unix-based platforms, see the manual page for the 'ulimit' command. Kernel or system reconfiguration may also be required.
For Windows-based platforms, see Microsoft Knowledge Base Article 196271 (Q196271).
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.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:54)
at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:93)
at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:133)
at com.mysql.cj.core.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:149)
at com.mysql.cj.mysqla.io.MysqlaSocketConnection.connect(MysqlaSocketConnection.java:83)
at com.mysql.cj.mysqla.MysqlaSession.connect(MysqlaSession.java:122)
at com.mysql.cj.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:1619)
... 32 more
Caused by: java.net.BindException: Address already in use: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.mysql.cj.core.io.StandardSocketFactory.connect(StandardSocketFactory.java:202)
at com.mysql.cj.mysqla.io.MysqlaSocketConnection.connect(MysqlaSocketConnection.java:57)
... 34 more
févr. 15, 2017 12:14:27 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFOS: Closing org.springframework.context.support.ClassPathXmlApplicationContext#41906a77: startup date [Wed Feb 15 12:12:59 CET 2017]; root of context hierarchy
févr. 15, 2017 12:14:27 PM org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean destroy
INFOS: Closing JPA EntityManagerFactory for persistence unit 'default'
If i understand correctly, connections to database are not closed correctly and the number of sockets used reach a limit. Problem is connections are normally managed by spring and should not stay open.
I dont want to increase this limit, just close and open a connection each time I insert or update something.
I think the key is to change the application context file, but couldn t find how.
Here are the applicationContext :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Activation annotations et scan des classes -->
<context:annotation-config />
<context:component-scan base-package="jpa" />
<!-- Specify the Hibernate properties setting file -->
<context:property-placeholder
location="classpath:hibernate.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- Creation EntityManagerFactory à partir de la dataSource -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="jpa" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
<property name="showSql" value="${hibernate.show_sql}" />
<property name="generateDdl" value="true" />
</bean>
</property>
<!-- <property name="jpaProperties"> -->
<!-- <props> -->
<!-- <prop key="hibernate.hbm2ddl.auto">${hibernate.action}"</prop> -->
<!-- </props> -->
<!-- </property> -->
</bean>
<!-- getionnaire transaction entityManagerFactory -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- activation de l'annotation #Transcationnal -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- activation translation d'execption -->
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"></bean>
</beans
and the property file :
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/calib?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&autoReconnect=true&useSSL=false
jdbc.username=root
jdbc.password=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=false
hibernate.action=create-drop
Edit : I tried to open and close the ClassPathXmlApplicationContext to renew the connection but the same error happens : java.net.BindException: Address already in use: connect
Edit 2 :
Dao :
package jpa.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import jpa.model.NewModelAttr;
#Repository
#Transactional
public class DaoAttrJpa implements DaoAttr{
#PersistenceContext
private EntityManager em;
#Override
public void create(NewModelAttr obj) {
em.persist(obj);
}
#Override
public void delete(NewModelAttr obj) {
em.remove(em.merge(obj));
}
#Override
public NewModelAttr update(NewModelAttr obj) {
return em.merge(obj);
}
#SuppressWarnings("unchecked")
#Override
public List<NewModelAttr> findAll() {
List<NewModelAttr> liste = null;
Query query = em.createNamedQuery("NewModelAttr.findAll", NewModelAttr.class);
liste = query.getResultList();
return liste;
}
#Override
public NewModelAttr findByPrimaryKey(Integer key) {
return em.find(NewModelAttr.class, key);
}
}
Singleton spring :
package jpa.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;
import jpa.dao.*;
#Repository
public class AccessDao {
private static ClassPathXmlApplicationContext context;
private static AccessDao instance = null;
#Autowired
private DaoProject daoProject;
#Autowired
private DaoLink daoLink;
#Autowired
private DaoPath daoPath;
#Autowired
private DaoRequirement daoRequirement;
#Autowired
private DaoScenario daoScenario;
#Autowired
private DaoStep daoStep;
#Autowired
private DaoAttr daoAttr;
#Autowired
private DaoCategory daoCategory;
// private AccessDao() {
// context = new ClassPathXmlApplicationContext("applicationContext.xml");
// daoProject = (DaoProject) context.getBean("daoProjectJpa");
// daoLink = (DaoLink) context.getBean("daoLinkJpa");
// daoPath = (DaoPath) context.getBean("daoPathJpa");
// daoRequirement = (DaoRequirement) context.getBean("daoRequirementJpa");
// daoScenario = (DaoScenario) context.getBean("daoScenarioJpa");
// daoStep = (DaoStep) context.getBean("daoStepJpa");
// daoAttr = (DaoAttr) context.getBean("daoAttrJpa");
// daoCategory = (DaoCategory) context.getBean("daoCategoryJpa");
// }
public static AccessDao getInstance() {
if (AccessDao.instance == null) {
context = new ClassPathXmlApplicationContext("applicationContext.xml");
AccessDao.instance = (AccessDao) context.getBean("accessDao");
}
return AccessDao.instance;
}
public DaoProject getDaoProject() {
return daoProject;
}
public void setDaoProject(DaoProject daoProject) {
this.daoProject = daoProject;
}
public DaoLink getDaoLink() {
return daoLink;
}
public void setDaoLink(DaoLink daoLink) {
this.daoLink = daoLink;
}
public DaoPath getDaoPath() {
return daoPath;
}
public void setDaoPath(DaoPath daoPath) {
this.daoPath = daoPath;
}
public DaoRequirement getDaoRequirement() {
return daoRequirement;
}
public void setDaoRequirement(DaoRequirement daoRequirement) {
this.daoRequirement = daoRequirement;
}
public DaoScenario getDaoScenario() {
return daoScenario;
}
public void setDaoScenario(DaoScenario daoScenario) {
this.daoScenario = daoScenario;
}
public DaoStep getDaoStep() {
return daoStep;
}
public void setDaoStep(DaoStep daoStep) {
this.daoStep = daoStep;
}
public DaoAttr getDaoAttr() {
return daoAttr;
}
public void setDaoAttr(DaoAttr daoAttr) {
this.daoAttr = daoAttr;
}
public DaoCategory getDaoCategory() {
return daoCategory;
}
public void setDaoCategory(DaoCategory daoCategory) {
this.daoCategory = daoCategory;
}
public static void close() {
if (instance != null) {
instance.destroy();
}
}
private void destroy() {
context.close();
instance=null;
}
}
Also open and close many times was just a test. I usually open at the start and close at the end.
Edit 3:
Here is a part of the code where i insert :
private List<NewModelProject> transformOldModelToNewModel(List<ProjectType> projectsFromXML) {
List<NewModelProject> projectsNewModel = new ArrayList<>();
for (ProjectType projectType : projectsFromXML) {
System.out.println("proj:" + projectType.getName());
NewModelProject project = new NewModelProject();
project.setBaseline(projectType.getBaseline());
project.setDescription(projectType.getDescription());
project.setId(Integer.parseInt(projectType.getId()));
project.setName(projectType.getName());
projectsNewModel.add(project);
dao.getDaoProject().create(project);
objectToUpdate.add(project);
manageCategories(projectType, project);
manageScenarios(projectType, project);
}
gestionTraceability();
return projectsNewModel;
}
Found the solution, thanks to M. Deinum !
I needed to replace DriverManagerDataSource with a BasicDataSource in applicationContext :
DriverManagerDataSource create a new connection for each request wich is problematic when we want to send a lot of request.
Guys I am new with Hibernate and I am struggling to make a hello world app work. Below I will post the exception I am getting as well as my code - with the hope maybe someone can spot other errors which I have and save me from "future" troubles.
Code:
package org.arpit.javapostsforlearning;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity(name = "User_table")
public class User {
#Id
int userId;
#Column(name = "User_Name")
String userName;
String userMessage;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserMessage() {
return userMessage;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
}
This:
package org.arpit.javapostsforlearning;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateMain {
public static void main(String[] args)
{
Configuration configuration=new Configuration();
configuration.configure();
configuration.addClass(org.arpit.javapostsforlearning.User.class);
ServiceRegistry sr= new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sf=configuration.buildSessionFactory(sr);
User user1=new User();
user1.setUserName("Arpit");
user1.setUserMessage("Hello world from arpit");
User user2=new User();
user2.setUserName("Ankita");
user2.setUserMessage("Hello world from ankita");
Session ss=sf.openSession();
ss.beginTransaction(); //saving objects to session
ss.save(user1);
ss.save(user2);
ss.getTransaction().commit();
ss.close();
}
}
And XMLS:
<?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.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://localhost:1433;database=Sandboxlearning;integratedSecurity=true</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</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">create</property>
<mapping class="User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
User.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="User" table="User_table">
<meta attribute="class-description">
This class contains the user detail.
</meta>
<id name="userId" type="int" column="userId">
<generator class="native"/>
</id>
<property name="userName" column="User_Name" type="string"/>
<property name="userMessage" column="userMessage" type="string"/>
</class>
</hibernate-mapping>
Exception:
Jun 28, 2016 7:17:15 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.0.Final}
Jun 28, 2016 7:17:15 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 28, 2016 7:17:15 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jun 28, 2016 7:17:15 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Exception in thread "main" org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not found : org/arpit/javapostsforlearning/User.hbm.xml : origin(org/arpit/javapostsforlearning/User.hbm.xml)
at org.hibernate.boot.spi.XmlMappingBinderAccess.bind(XmlMappingBinderAccess.java:56)
at org.hibernate.boot.MetadataSources.addResource(MetadataSources.java:274)
at org.hibernate.boot.MetadataSources.addClass(MetadataSources.java:262)
at org.hibernate.cfg.Configuration.addClass(Configuration.java:513)
at org.arpit.javapostsforlearning.HibernateMain.main(HibernateMain.java:14)
The XMLS are stored under src folder.
Here is also screen shot of my App
image
Take a look to: <mapping class="User.hbm.xml"/>. But you using resource. You are able to use class when you saying that map me class for that, but you want to map resource. So just use
<mapping resource="User.hbm.xml"/>
Previously I used JDBC in my application and it was running very fast, but I have modified it to use Hibernate which made it too slow, especially when it needs to open a page that has a dropdown box in it. It takes much longer in compare to JDBC, to open this kind of pages.
If I try to access a table with foreign keys it takes much longer.
My server is GlassFish and I am usingfollowing version of hibernate.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.10.Final</version>
<type>jar</type>
</dependency>
The questions are why is it to slow in compare to JDBC and do I need to have the following lin before each session.beginTransaction() ?
session = HibernateUtil.getSessionFactory().openSession();
Take the following one as an example, it has a dropdown box that need to be populated once the page is opened.
HibernateUtil.java
package com.myproject.util;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
private static SessionFactory configureSessionFactory() {
try {
System.out.println("1");
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new
ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
System.out.println("2");
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
System.out.println("3");
return sessionFactory;
} catch (HibernateException e) {
System.out.append("** Exception in SessionFactory **");
e.printStackTrace();
}
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return configureSessionFactory();
}
}
MyClassModel.java
public class MyClassModel extends HibernateUtil {
private Session session;
public Map populatedropdownList() {
Map map = new HashMap();
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List<MyListResult> temp = null;
try{
temp = retrieveItems();
System.err.println("size:" + temp.size());
for(int i=0;i<temp.size();i++){
map.put(temp.get(i).getId(),temp.get(i).getName());
}
session.getTransaction().commit();
session.close();
return map;
}catch(Exception e){
e.printStackTrace();
}
return map;
}
private List <MyListResult> retrieveItems(){
Criteria criteria = session.createCriteria(MyTable.class, "MyTable");
ProjectionList pl = Projections.projectionList();
pl.add(Projections.property("MyTable.id").as("id"));
pl.add(Projections.property("MyTable.name").as("name"));
criteria.setProjection(pl);
criteria.setResultTransformer(new
AliasToBeanResultTransformer(MyListResult.class));
return criteria.list();
}
MyListResult.java
public class MyListResult implements Serializable {
private int id;
private String Name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
}
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>
<!-- Database connection settings -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/MyDatabase
</property>
<property name="connection.username">root</property>
<property name="connection.password"></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.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 class="com.MyProject.MyTable" />
</session-factory>
</hibernate-configuration>
Console is as following
INFO: in myform
INFO: 1
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
INFO: HHH000041: Configured SessionFactory: null
INFO: 2
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
INFO: HHH000115: Hibernate connection pool size: 1
INFO: HHH000006: Autocommit mode: false
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL
[jdbc:mysql://localhost:3306/MyDatabase]
INFO: HHH000046: Connection properties: {user=root, password=****}
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
INFO: HHH000397: Using ASTQueryTranslatorFactory
INFO: HHH000228: Running hbm2ddl schema update
INFO: HHH000102: Fetching database metadata
INFO: HHH000396: Updating schema
INFO: HHH000261: Table found: MyDatabase.MyTable
INFO: HHH000037: Columns: [id, name, age, xx, yy]
INFO: HHH000126: Indexes: [primary]
INFO: HHH000232: Schema update complete
INFO: Hibernate: select this_.id as y0_, this_.name as y1_ from MyTable this_
SEVERE: size:4
Usually in the application you shouldn't build the session factory each time when you need the session. That's what actually needed by application to use the hibernate. If you want to manage the session manually then you write the HibernateUtil making it singleton. Initially, build the session factory in the static initializer block
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<>();
private static SessionFactory sessionFactory;
static {
try {
sessionFactory = configureSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateUtil() {
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session getSession() throws HibernateException {
Session session = threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
sessionFactory = configureSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
think that's enough addition to your code to run your application.
While I don't have any direct experience with Hibernate, I do with NHibernate, which is modeled after the Java version, so this should still be correct...
Building up the SessionFactory takes time, all the more so since, if I'm reading the configuration right, you're having it check for schema changes between your models and the database when it does start.
What you should do instead is create the SessionFactory once on startup (or upon the first use of data access, depending on when you want to pay the cost of setting up Hibernate) and use that through the lifetime of your app.
What I tend to do is something roughly like this (rough psuedocode, since my Java is rusty):
Session getSession()
{
if(sessionFactory == null)
buildSessionFactory()
return sessionFactory.OpenSession()
}
(Of course this doesn't take into account any possible race conditions with threading). This should hopefully see a rather large performance boost. Keep in mind that ORMs are almost never as fast as hand-coded SQL due to the additional mapping layers, but it's a trade off between performance and ease of coding.