I try to implement a CRUD application in Java using JPA with Hibernate.
I have two independent tests that act on two different database tables. When I run one of these tests, the corresponding table is populated correctly, but when I run the other test the table that was previously populated is emptied and the other table is filled.
This is my configuration.cfg.xml file for the configuration of hibernate:
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.connection.url">
jdbc:sqlite:/Users/th3g3ntl3man/Repository/assignment3/src/main/resources/database.db
</property>
<property name="dialect">com.enigmabridge.hibernate.dialect.SQLiteDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.current_session_context_class">
org.hibernate.context.internal.ThreadLocalSessionContext
</property>
<mapping class="entity.User"/>
<mapping class="entity.Topic"/>
<mapping class="entity.Image"/>
</session-factory>
</hibernate-configuration>
I suppose that the problem was in the property hbm2ddl.auto, thus I try to change the value from create to update but when I compile one test I works correctly but when I run a second test the test crash with this stack trace:
java.lang.ExceptionInInitializerError
at util.Operation.getByPrimaryKey(Operation.java:34)
at dao.TopicDAO.create(TopicDAO.java:22)
at entity.TopicTest.setUp(TopicTest.java:22)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.util.NoSuchElementException
at java.base/java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.populateTablesWithColumns(InformationExtractorJdbcDatabaseMetaDataImpl.java:369)
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:207)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
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:462)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at util.HibernateUtil.init(HibernateUtil.java:11)
at util.HibernateUtil.<clinit>(HibernateUtil.java:8)
For the all code, this is the repository link
Related
I use hsqldb 2.4.0 library for test my DAO layer (Hibernate 5.2.10). I create separate hibernate.cfg.xml for hsqldb in dir test/resources/hibernate.cfg.xml. But when I run test then get CommandAcceptanceException:
2017-08-04T20:34:35.755+0300 WARN GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:375)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:359)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applyConstraintDropping(SchemaDropperImpl.java:331)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:230)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:154)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:126)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:112)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:144)
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 org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at ru.pravvich.dao.DAOImplTest.before(DAOImplTest.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
Hibernate: drop table propose if exists
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
Hibernate: drop table users if exists
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: PUBLIC.PROPOSE
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.execute(Unknown Source)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
... 37 more
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: PUBLIC.PROPOSE
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.SchemaManager.getUserTable(Unknown Source)
at org.hsqldb.ParserDDL.compileAlterTable(Unknown Source)
at org.hsqldb.ParserDDL.compileAlter(Unknown Source)
at org.hsqldb.ParserCommand.compilePart(Unknown Source)
at org.hsqldb.ParserCommand.compileStatements(Unknown Source)
at org.hsqldb.Session.executeDirectStatement(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
... 40 more
It's not a compatible version of syntax (If I understand correctly). But in hibernate.cfg.xml the version defined HSQLDialect:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="http://www.hibernate.org/xsd/orm/cfg">
<session-factory>
<property name="connection.url">jdbc:hsqldb:mem:auto_mag;sql.enforce_size=false</property>
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="ru/pravvich/model/User.hbm.xml" />
<mapping resource="ru/pravvich/model/Propose.hbm.xml" />
</session-factory>
</hibernate-configuration>
Help me to find the mistake. Thank You.
i'm defining an one entity and hibernate is my provider.this is persistence.xml :
<persistence-unit name="ordersUnit">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<mapping-file>com/jj/entityZone/OrdersViewEntity.xml</mapping-file>
<class>com.jj.entityZone.OrdersViewEntity</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:sqlserver://localhost\MSSQLSERVER;databaseName=JbDB"/>
<property name="hibernate.connection.driver_class" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="hibernate.connection.username" value="xxx"/>
<property name="hibernate.connection.password" value="xxx"/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
and 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.connection.url">jdbc:sqlserver://localhost\MSSQLSERVER;databaseName=JbDB</property>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.username">uuu</property>
<property name="hibernate.connection.password">xxx</property>
</session-factory>
this is java code (used in singleton bean):
SessionFactory sessionFactory =
new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ordersUnit");
EntityManager entitymanager = emfactory.createEntityManager();
entitymanager.getTransaction().begin();
OrdersViewEntity ov = new OrdersViewEntity();
Query query = entitymanager.createNativeQuery("SELECT * FROM ORDERS_VIEW ", OrdersViewEntity.class);
List<OrdersViewEntity> list = query.getResultList();
for (OrdersViewEntity n : list) {
System.out.println("OV:" + n.getIdQueue());
System.out.println("OV:" + n.getIdCnt());
}
entitymanager.getTransaction().commit();
System.out.println("Size : " + list.size());
entitymanager.close();
emfactory.close();
but rather i get error :
javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:750)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:700)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:505)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4542)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2021)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1992)
at com.sun.ejb.containers.BaseContainer.callEJBTimeout(BaseContainer.java:4029)
at com.sun.ejb.containers.EJBTimerService.deliverTimeout(EJBTimerService.java:1224)
at com.sun.ejb.containers.EJBTimerService.access$000(EJBTimerService.java:92)
at com.sun.ejb.containers.EJBTimerService$TaskExpiredWork.run(EJBTimerService.java:1954)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: ordersUnit] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:967)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at com.jabolsa.jbeans.PlayBoardBean.startReadOrders(PlayBoardBean.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4762)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:834)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:73)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:895)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:834)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundTimeout(SystemInterceptorProxy.java:145)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:895)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:834)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:374)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4734)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4722)
at com.sun.ejb.containers.BaseContainer.callEJBTimeout(BaseContainer.java:4000)
... 8 more
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.jabolsa.entityZone.LocationsQuarterEntity column: id_province (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:835)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:853)
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:875)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:607)
at org.hibernate.mapping.RootClass.validate(RootClass.java:265)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:451)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:889)
... 43 more
]]
QUIZ 1: is it ok?
QUIZ 2: if i suppose to use JNDI what can i do? how to define this?
QUIZ 3: why this exception "Caused by: javax.persistence.PersistenceException: [PersistenceUnit: ordersUnit] Unable to build Hibernate SessionFactory" thrown ?
i'm using intellij and glassfish(Payara) . how to make SessionFactoy and use with entity manager?
I am trying to connect to h2 database from a hibernate project.
It worked fine with Oracle but I need to migrate to H2.
The only things that I have changed are the driver and the hibernate.cfg.xml
pom.xml
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
hibernate.cfg.xml file
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:tcp://localhost/~/test;IFEXISTS=TRUE</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<mapping class="com.wkfsfrc.drools.dummy.runtimeload.Employee"/>
</session-factory>
the exception that I get is:
May 19, 2015 11:32:49 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Initial SessionFactory creation failed.org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
java.lang.ExceptionInInitializerError
at com.wkfsfrc.drools.dummy.runtimeload.HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
at com.wkfsfrc.drools.dummy.runtimeload.HibernateUtil.<clinit>(HibernateUtil.java:9)
at com.wkfsfrc.drools.dummy.runtimedataload.RuntimeDataLoadTest.<init>(RuntimeDataLoadTest.java:25)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:122)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
at com.wkfsfrc.drools.dummy.runtimeload.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
... 27 more
Caused by: org.h2.jdbc.JdbcSQLException: Connection is broken: "java.net.ConnectException: Connection refused: connect: localhost" [90067-178]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:344)
at org.h2.message.DbException.get(DbException.java:167)
at org.h2.engine.SessionRemote.connectServer(SessionRemote.java:438)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:315)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:107)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:91)
at org.h2.Driver.connect(Driver.java:74)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
... 41 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at org.h2.util.NetUtils.createSocket(NetUtils.java:123)
at org.h2.util.NetUtils.createSocket(NetUtils.java:103)
at org.h2.engine.SessionRemote.initTransfer(SessionRemote.java:100)
at org.h2.engine.SessionRemote.connectServer(SessionRemote.java:434)
... 46 more
What else do I need to do, to successfully connect to H2.
Do I need to start H2 before connecting to it or Hibernate does this? DONO
Any advice is appreciated!
You seem not to have started the H2 server. Based on your URL, you're using tcp connection, ie the server has to be started first.
2 ways out:
you have a java master program in which you should start the server like this:
org.h2.tools.Server.createTcpServer().start();
or you could start it manually prior to your connection attempt like this:
java -cp h2*.jar org.h2.tools.Server
I noticed you're using ifexists=true. Connection will still be refused if the database does not exist prior to connection.
I am trying to run hibernate in a Java project that is referenced by a web project. Simple enough except that I can't get hibernate to connect to my database. I have a lot of people describing this problem and getting tons of answers however none seem to work for me.
This is how my hibernate.cfg.xml looks like:
<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql//localhost:3306/dbname</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">commander</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">50</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>
<!-- Enable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/amakena/profile/mapping/Credentials.hbm.xml"/>
<mapping resource="com/amakena/profile/mapping/Profile.hbm.xml"/>
<mapping resource="com/amakena/profile/mapping/City.hbm.xml"/>
<mapping resource="com/amakena/profile/mapping/Country.hbm.xml"/>
<mapping resource="com/amakena/profile/mapping/Gender.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I debugged the code to DriverManagerConnectionProvider class, the exception is thrown attempting the getConnection() method
Connection conn = DriverManager.getConnection(url, connectionProps);
I checked the url and connectionProps and they are the ones in hibernate.cfg.xml
I have added mysql-connector-java-3.1.14-bin in my tomcat \lib folder and I can see it in eclipse under Libraries>Apache Tomcat v6.0>. I also added it to my %Javahome%\lib\ext and my CLASSPATH variable (which I know is useless by I am kindda desperate).
I made sure my driver is installed properly by running the following code just before the session.beginTransaction() which in turn leads to DriverManagerConnectionProvider.getConnection()
Class.forName("com.mysql.jdbc.Driver");
Properties connectionProperties = new Properties();
connectionProperties.put("user", "root");
connectionProperties.put("password", "root");
DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname", connectionProperties);
I noticed that emitting the first line causes the same exception.
Exception thrown
WARNING: Method execution failed:
org.hibernate.exception.JDBCConnectionException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:99)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:160)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:81)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1473)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:345)
at $Proxy0.beginTransaction(Unknown Source)
at com.amakena.profile.dao.CredentialsDao.hydrate(CredentialsDao.java:45)
at com.amakena.profile.ProfileManager.login(ProfileManager.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.directwebremoting.impl.ExecuteAjaxFilter.doFilter(ExecuteAjaxFilter.java:34)
at org.directwebremoting.impl.DefaultRemoter$1.doFilter(DefaultRemoter.java:428)
at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:431)
at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:283)
at org.directwebremoting.servlet.PlainCallHandler.handle(PlainCallHandler.java:52)
at org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:101)
at org.directwebremoting.servlet.DwrServlet.doPost(DwrServlet.java:146)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql//localhost:3306/dbname
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:133)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
... 37 more
WARNING: --Erroring: batchId[24] message[org.hibernate.exception.JDBCConnectionException: Cannot open connection]
I appreciate all the help I could get. Thanks in advance.
Versions Used: Tomcat v6.0 - Hibernate 3.6.6 - Java 6 - Eclipse 3.5.2 R35x
You forgot the colon after "mysql":
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/dbname</property>
Here's the doc for the URL format:
jdbc:mysql://[host][,failoverhost...][:port]/[database]
No suitable driver always means that the driver JAR was loaded, but your URL syntax is incorrect.
jdbc:mysql://localhost:3306/dbname
You are missing the : after mysql
Another reason is that the driver class is not found, make sure your driver class is successfully loaded.
I have issue with reverse engineering from database using hibernate 5. I am able to generate the hibernate.reveng.xml file but when i run using the Hibernate Code Generation Configurations, it give me the error as stated below.
I have tried with adding "hibernate." to my xml files but same thing, i can generate the hibernate.reveng.xml but not able to run Hibernate Code Generation Configurations.
This is my xml file:
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.password">Password123!</property>
<property name="connection.url">jdbc:sqlserver://localhost:1433;databaseName=TestDB</property>
<property name="connection.username">sa</property>
<property name="dialect">org.hibernate.dialect.SQLServer2012Dialect</property>
</session-factory>
</hibernate-configuration>
This is the error i am facing.
org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:257)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.cfg.JDBCMetaDataConfiguration.handleTypes(JDBCMetaDataConfiguration.java:231)
at org.hibernate.cfg.JDBCMetaDataConfiguration.getMetadataCollector(JDBCMetaDataConfiguration.java:90)
at org.hibernate.cfg.JDBCMetaDataConfiguration.getMetadataBuildingContext(JDBCMetaDataConfiguration.java:105)
at org.hibernate.cfg.JDBCMetaDataConfiguration.readFromJDBC(JDBCMetaDataConfiguration.java:123)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.jboss.tools.hibernate.runtime.common.Util.invokeMethod(Util.java:43)
at org.jboss.tools.hibernate.runtime.common.AbstractConfigurationFacade.readFromJDBC(AbstractConfigurationFacade.java:216)
at org.hibernate.eclipse.console.common.ConsoleExtension$2.execute(ConsoleExtension.java:308)
at org.hibernate.console.execution.DefaultExecutionContext.execute(DefaultExecutionContext.java:63)
at org.hibernate.console.ConsoleConfiguration.execute(ConsoleConfiguration.java:108)
at org.hibernate.eclipse.console.common.ConsoleExtension.buildConfiguration(ConsoleExtension.java:266)
at org.hibernate.eclipse.console.common.ConsoleExtension.runExporters(ConsoleExtension.java:174)
at org.hibernate.eclipse.console.common.ConsoleExtension.launchExporters(ConsoleExtension.java:110)
at org.hibernate.eclipse.launch.CodeGenerationLaunchDelegate.launch(CodeGenerationLaunchDelegate.java:266)
at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:885)
at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:739)
at org.eclipse.debug.internal.ui.DebugUIPlugin.buildAndLaunch(DebugUIPlugin.java:1039)
at org.eclipse.debug.internal.ui.DebugUIPlugin$8.run(DebugUIPlugin.java:1256)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
Try This.
Change <property name="dialect">org.hibernate.dialect.SQLServer2012Dialect</property> to <property name="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</property>
I ended up deleting the whole configuration file and redo all the step to reverse engineer my pojo as per what I have posted and is working now. But I have not idea why.