I'm getting weird problem. I'm trying to do an integration testing but the Entity Manager creator is not working.
<? xml version = "1.0" encoding = "UTF-8"?>
<persistence xmlns = "http://java.sun.com/xml/ns/persistence"
xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation = "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version = "2.0">
<persistence-unit name = "db-test" transaction-type = "RESOURCE_LOCAL">
<provider> org.hibernate.jpa.HibernatePersistenceProvider </ provider>
<class> br.com.e2pd.model.Grupo </ class>
<properties>
<property name = "javax.persistence.jdbc.url" value = "jdbc: hsqldb: mem: db-test" />
<property name = "javax.persistence.jdbc.user" value = "sa" />
<property name = "javax.persistence.jdbc.password" value = "" />
<property name = "javax.persistence.schema-generation.database.action" value = "drop-and-create" />
<property name = "hibernate.show_sql" value = "true" />
<property name = "hibernate.hbm2ddl.auto" value = "update" />
</ properties>
</ persistence-unit>
</ persistence>
public class RepositoryTest {
protected static EntityManagerFactory factory;
protected static EntityManager em;
#BeforeClass
public static void setUpPersistence() {
factory = Persistence.createEntityManagerFactory("db-test");
em = factory.createEntityManager();
em.getTransaction().begin();
}
#AfterClass
public static void tearDown() {
em.getTransaction().commit();
em.close();
factory.close();
}
}
public class GrupoRepositoryTest extends RepositoryTest {
private GrupoRepository repository;
#Before
public void setUp() {
this.repository = new GrupoRepositoryImpl(em);
}
}
#Entity
#Table(name = "grupos")
public class Grupo implements Model{
#Id
#GeneratedValue
#Column(name = "id")
private Long id;
#Column(name = "nome")
private String nome;
public Grupo() {
}
public Grupo(Long id, String nome) {
this.id = id;
this.nome = nome;
}
//gets and sets
}
The log comes up here:
20: 53: 28.484 INFO [LogHelper] HHH000204: Processing PersistenceUnitInfo [
name: DB-test
...]
20: 53: 28.582 INFO [Version] HHH000412: Hibernate Core 5.0.2.Final {}
20: 53: 28.584 INFO [Environment] HHH000206: hibernate.properties not found
20: 53: 28.586 INFO [Environment] HHH000021: Bytecode provider name: Javassist
20: 53: 39.198 INFO [Version] HCANN000001: Hibernate Commons Annotations 5.0.0.Final {}
20: 55: 45.714 WARN [DriverManagerConnectionProviderImpl] HHH000402: Using Hibernate built-in connection pool (not for production use!)
20: 55: 45.732 INFO [DriverManagerConnectionProviderImpl] HHH000401: using driver [null] at URL [jdbc: hsqldb: mem: db-test]
20: 55: 45.733 INFO [DriverManagerConnectionProviderImpl] HHH000046: Connection properties: user = {s}
20: 55: 45.733 INFO [DriverManagerConnectionProviderImpl] HHH000006: Autocommit mode: false
20: 55: 45.740 INFO [DriverManagerConnectionProviderImpl] HHH000115: Hibernate connection pool size: 20 (min = 1)
STOPS HERE!
And gives the exception Caused by: java.sql.SQLException: No suitable driver found for jdbc: hsqldb: mem: db-test.
To solve this exception I did it in the setUpPersistence() ( even not knowing if it is the best solution ):
try {
Class.forName ("org.hsqldb.jdbcDriver");
connection = DriverManager.getConnection ("jdbc: hsqldb: mem: db-test", "sa", "");
} Catch (Exception ex) {
ex.printStackTrace ();
}
Thereafter when road testing gives the error:
java.lang.NoSuchMethodError: javax.persistence.Table.indexes () [Ljavax / persistence / Index;
at org.hibernate.cfg.annotations.EntityBinder.processComplementaryTableDefinitions(EntityBinder.java:1080)
at org.hibernate.cfg.AnnotationBinder.bindClass (AnnotationBinder.java:765)
at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.processEntityHierarchies(AnnotationMetadataSourceProcessorImpl.java:245)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.processEntityHierarchies(MetadataBuildingProcess.java:222)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:265)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:770)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:797)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
at javax.persistence.Persistence.createEntityManagerFactory (Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory (Persistence.java:47)
at unit.br.com.e2pd.common.RepositoryTest.setUpPersistence (RepositoryTest.java:36)
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)
org.junit.runners.model.FrameworkMethod at $ 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.run (ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run (JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run (TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests (RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests (RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run (RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main (RemoteTestRunner.java:192)
java.lang.NullPointerException
at unit.br.com.e2pd.common.RepositoryTest.tearDown (RepositoryTest.java:43)
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)
org.junit.runners.model.FrameworkMethod at $ 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.RunAfters.evaluate (RunAfters.java:33)
at org.junit.runners.ParentRunner.run (ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run (JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run (TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests (RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests (RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run (RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main (RemoteTestRunner.java:192)
Maybe this one is related to JPA version, see this question NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index
Hope helps
Related
I have a small project that I want to integrate with lucene and hibernate:
This is the bean file:
package com.domain.java;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.search.annotations.Analyzer;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
#Entity
#Indexed
#Analyzer(impl = org.apache.lucene.analysis.standard.StandardAnalyzer.class)
public class TempFile {
#Field(store = Store.YES)
private String iconName;
#Field(store = Store.YES)
private String name;
#Id
#DocumentId
#Field(store = Store.YES)
private String path;
#Field(store = Store.YES)
private boolean mightHaveThumbnail;
#Field(store = Store.YES)
private boolean folder;
#Field(store = Store.YES)
private boolean file;
public String getIconName() {
return iconName;
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
public boolean isMightHaveThumbnail() {
return mightHaveThumbnail;
}
public boolean isFolder() {
return folder;
}
public boolean isFile() {
return file;
}
public void setIconName(String iconName) {
this.iconName = iconName;
}
public void setName(String name) {
this.name = name;
}
public void setPath(String path) {
this.path = path;
}
public void setMightHaveThumbnail(boolean mightHaveThumbnail) {
this.mightHaveThumbnail = mightHaveThumbnail;
}
public void setFolder(boolean folder) {
this.folder = folder;
}
public void setFile(boolean file) {
this.file = file;
}
}
And this the Hibernate file:
package com.domain.java;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.service.ServiceRegistry;
public class HibernateTest {
public static void main(String[] args) {
TempFile mm = new TempFile();
mm.setFile(true);
mm.setPath("patdsaasdsadahswdsaaad "+new Date());
mm.setName("nasdasassadasaeeassaaasddas "+new Date());
Properties properties = new Properties();
try {
properties.load(new FileInputStream("./resources/postgres/hibernate.properties"));
// readAPropertyFile("./resources/postgres/hibernate.properties");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Configuration configuration = new Configuration();
File file = new File("./resources/postgres/hibernate.cfg.xml");
System.out.println(file.exists());
configuration.mergeProperties(properties);
configuration.configure(file);
configuration.addAnnotatedClass(TempFile.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
FullTextSession fullTextSession = Search.getFullTextSession(session);
try {
fullTextSession.createIndexer().startAndWait();
fullTextSession.beginTransaction();
fullTextSession.close();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// session.save(mm);
// session.getTransaction().commit();
session.close();
// now lets pull events from the database and list them
session = sessionFactory.openSession();
session.beginTransaction();
List result = session.createQuery("from TempFile").list();
for ( TempFile event : (List<TempFile>) result ) {
System.out.println( "Event (" + event.getPath() + ") : " + event.getPath() );
System.out.println( "Event (" + event.getName() + ") : " + event.getName() );
}
session.getTransaction().commit();
session.close();
}
private static void readAPropertyFile(String propertiesFilePath) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(propertiesFilePath);
// load a properties file
prop.load(input);
// get the property value and print it out
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = prop.getProperty(key);
System.out.println("Key : " + key + ", Value : " + value);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
The configuration files:
<?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>.
-->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<!-- <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost/TestDB</property> -->
<!-- Echo all executed SQL to stdout -->
<!-- >property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hibernate.search.default.directory_provider">filesystem</property>
-->
<!--
< Enable Hibernate's automatic session context management >
<property name="current_session_context_class">thread</property>
<property name="cache.use_query_cache">true</property>
<property name="cache.use_second_level_cache">true</property>
<property name="cache.use_structured_entries">true</property>
<property name="cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>
<property name="net.sf.ehcache.configurationResourceName">/hibernate-config/ehcache.xml</property>
mapping resource="hibernate-config/domain/Event.hbm.xml"/>
<mapping resource="hibernate-config/domain/Person.hbm.xml"/>
<mapping resource="hibernate-config/domain/PhoneNumber.hbm.xml"/>
<mapping resource="hibernate-config/domain/Account.hbm.xml"/>
<mapping resource="hibernate-config/domain/HolidayCalendar.hbm.xml"/>
<mapping resource="hibernate-config/domain/Item.hbm.xml"/-->
<!--
<mapping class="com.domain.java.TempFile"/>
org.hibernate.search.store.impl.RAMDirectoryProvider
-->
<!-- Would set this in production application. Index stored on disk. -->
<property name="hibernate.search.default.directory_provider">
org.hibernate.search.store.impl.FSDirectoryProvider
</property>
<property name="hibernate.search.default.indexBase">c:\aatemp\lucene\indexes</property>
</session-factory>
</hibernate-configuration>
The property file
######################
### Query Language ###
######################
## define query language constants / function names
hibernate.query.substitutions yes 'Y', no 'N'
## select the classic query parser
#hibernate.query.factory_class org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory
#################
### Platforms ###
#################
## JNDI Datasource
#hibernate.connection.datasource jdbc/test
#hibernate.connection.username db2
#hibernate.connection.password db2
## PostgreSQL
hibernate.dialect org.hibernate.dialect.PostgreSQLDialect
hibernate.connection.driver_class org.postgresql.Driver
hibernate.connection.url jdbc:postgresql://localhost:5432/hibernatedb
hibernate.connection.username postgres
hibernate.connection.password xxxxxxxx
hibernate.hbm2ddl.auto=update
show_sql=true
#Lucene
hibernate.search.default.directory_provider filesystem
hibernate.search.default.indexBase c:/var/lucene/indexes
hibernate.search.default.locking_strategy simple
I am getting following exception running the above code:
May 27, 2016 6:39:19 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
May 27, 2016 6:39:19 AM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
May 27, 2016 6:39:19 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
true
May 27, 2016 6:39:19 AM 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.
May 27, 2016 6:39:19 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator
instantiateProxoolProvider
WARN: HHH000209: proxool properties were encountered, but the proxool provider class was not found on the classpath; these
properties are going to be ignored.
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/hibernatedb]
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
buildCreator
INFO: HHH10001003: Autocommit mode: false
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
May 27, 2016 6:39:19 AM org.hibernate.dialect.Dialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl
useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
May 27, 2016 6:39:19 AM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#10aa41f2
May 27, 2016 6:39:19 AM org.hibernate.envers.boot.internal.EnversServiceImpl configure
INFO: Envers integration enabled? : true
May 27, 2016 6:39:20 AM org.hibernate.search.engine.Version
INFO: HSEARCH000034: Hibernate Search 5.5.2.Final
May 27, 2016 6:39:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:postgresql://localhost:5432/hibernatedb]
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.lucene.index.IndexWriterConfig.setWriteLockTimeout(J)Lorg/apache/lucene/index/IndexWriterConfig;
at org.hibernate.search.store.spi.DirectoryHelper.initializeIndexIfNeeded(DirectoryHelper.java:57)
at org.hibernate.search.store.impl.DirectoryProviderHelper.createFSIndex(DirectoryProviderHelper.java:128)
at org.hibernate.search.store.impl.FSDirectoryProvider.initialize(FSDirectoryProvider.java:53)
at org.hibernate.search.store.spi.BaseDirectoryProviderService.initialize(BaseDirectoryProviderService.java:64)
at org.hibernate.search.store.spi.BaseDirectoryProviderService.create(BaseDirectoryProviderService.java:52)
at org.hibernate.search.indexes.spi.DirectoryBasedIndexManager.createDirectoryProvider(DirectoryBasedIndexManager.java:230)
at org.hibernate.search.indexes.spi.DirectoryBasedIndexManager.initialize(DirectoryBasedIndexManager.java:90)
at org.hibernate.search.indexes.impl.IndexManagerHolder.createIndexManager(IndexManagerHolder.java:256)
at org.hibernate.search.indexes.impl.IndexManagerHolder.createIndexManager(IndexManagerHolder.java:513)
at org.hibernate.search.indexes.impl.IndexManagerHolder.createIndexManagers(IndexManagerHolder.java:482)
at org.hibernate.search.indexes.impl.IndexManagerHolder.buildEntityIndexBinding(IndexManagerHolder.java:91)
at org.hibernate.search.spi.SearchIntegratorBuilder.initDocumentBuilders(SearchIntegratorBuilder.java:358)
at org.hibernate.search.spi.SearchIntegratorBuilder.buildNewSearchFactory(SearchIntegratorBuilder.java:199)
at org.hibernate.search.spi.SearchIntegratorBuilder.buildSearchIntegrator(SearchIntegratorBuilder.java:117)
at org.hibernate.search.hcore.impl.HibernateSearchSessionFactoryObserver.sessionFactoryCreated(HibernateSearchSessionFactoryObserver.java:75)
at org.hibernate.internal.SessionFactoryObserverChain.sessionFactoryCreated(SessionFactoryObserverChain.java:35)
at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:520)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at com.domain.java.HibernateTest.main(HibernateTest.java:48)
The com.domain.java.TempFile folder is created at the lucene index path but the folder is empty and the above exception is trowed.
The real problem is here:
org.apache.lucene.index.IndexWriterConfig.setWriteLockTimeout(J)Lorg/apache/lucene/index/IndexWriterConfig;
You have a dependency issue: the Lucene version you are using is not compatible with the version of Hibernate Search you're using.
Check your dependencies and fix them and your issue should go away.
This is my output it shows that I could not get a constructor from org.hibernate.persister.entity.SingleTableEntityPersister. As far as I can tell it has managed to access the log on to the database. The error starts soon after that.
Jan 21, 2016 9:19:44 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.6.Final}
Jan 21, 2016 9:19:44 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 21, 2016 9:19:44 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 21, 2016 9:19:45 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jan 21, 2016 9:19:45 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Jan 21, 2016 9:19:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jan 21, 2016 9:19:47 PM `enter code here`org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/rhs]
Jan 21, 2016 9:19:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Jan 21, 2016 9:19:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jan 21, 2016 9:19:47 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jan 21, 2016 9:19:48 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Exception in thread "main" org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:123)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:346)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at JavaUtil.main(JavaUtil.java:20)
Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:91)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:116)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:388)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:509)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:124)
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 org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
... 6 more
Caused by: java.lang.reflect.InvocationTargetException
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 org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:88)
... 15 more
Caused by: org.hibernate.PropertyNotFoundException: Could not locate setter method for property [Profession#SALARY]
at org.hibernate.internal.util.ReflectHelper.findSetterMethod(ReflectHelper.java:532)
at org.hibernate.property.access.internal.PropertyAccessBasicImpl.<init>(PropertyAccessBasicImpl.java:44)
at org.hibernate.property.access.internal.PropertyAccessStrategyBasicImpl.buildPropertyAccess(PropertyAccessStrategyBasicImpl.java:27)
at org.hibernate.mapping.Property.getGetter(Property.java:299)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:270)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:145)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:63)
... 20 more
This is a simple POJO class
import javax.persistence.*;
public class Profession {
private int EDUCATION;
private int HOURS;
private String JOB_OUTLOOK;
private String JOBTITLE;
private double SALARY;
private String UPWARD_MOBILITY;
public Profession() {
}
public int getEDUCATION() {
return EDUCATION;
}
public void setEDUCATION(int eDUCATION) {
EDUCATION = eDUCATION;
}
public int getHOURS() {
return HOURS;
}
public void setHOURS(int hOURS) {
HOURS = hOURS;
}
public String getJOB_OUTLOOK() {
return JOB_OUTLOOK;
}
public void setJOB_OUTLOOK(String jOB_OUTLOOK) {
JOB_OUTLOOK = jOB_OUTLOOK;
}
public String getJOBTITLE() {
return JOBTITLE;
}
public void setJOBTITLE(String jOBTITLE) {
JOBTITLE = jOBTITLE;
}
public double getSALARY() {
return SALARY;
}
public void setSALRAY(double sALARY) {
SALARY = sALARY;
}
public String getUPWARD_MOBILITY() {
return UPWARD_MOBILITY;
}
public void setUPWARD_MOBILITY(String uPWARD_MOBILITY) {
UPWARD_MOBILITY = uPWARD_MOBILITY;
}
}
This is my main class
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.Scanner;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class JavaUtil {
public JavaUtil() {
}
public static void main(String[] args) throws IOException {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Profession p = new Profession();
// closing session
Transaction tx = session.beginTransaction();
session.save(p);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}
This is my hibernate config file
<?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>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/rhs </property>
<property name="connection.user">root</property>
<property name="connection.password">root</property>
<!-- Related to the connection END -->
<!-- Related to hibernate properties START -->
<property name="show_sql">true </property>
<property name="dialet">org.hibernate.dialect.MySqlDialect </property>
<property name="hbm2ddl.auto">update </property>
<!-- Related to hibernate properties END -->
<!-- Related to mapping START -->
<mapping resource="profession.hbm.xml" />
<!-- Related to the mapping END -->
</session-factory>
</hibernate-configuration>
This is xml mapping
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Profession" table="profession">
<id name="JOBTITLE" column="JOBTITLE" >
<generator class="assigned" />
</id>
<property name="EDUCATION"/>
<property name="HOURS"/>
<property name="JOB_OUTLOOK"/>
<property name="SALARY"/>
<property name="UPWARD_MOBILITY"/>
</class>
</hibernate-mapping>
Please change your property name to follow the POJO rule
public class Profession {
private int education;
private int hours;
private String jobOutlook;
private String jobTitle;
private double salary;
private String upwardMobility;
.....
}
Looking for help with an intermittent error. Following extract is from the log file. Can't think what else to add but I will add more if needed.
13 Oct 2015 14:37:43,691 2746599 [pool-1-thread-1] INFO snbts.proteus.integrationengine.IntegrationThread - Processing batch: 16888445 on integration Queue 1
13 Oct 2015 14:37:46,831 2749739 [pool-1-thread-2] INFO snbts.proteus.integrationengine.IntegrationThread - Queue 2 is alive.
13 Oct 2015 14:37:52,706 2755614 [pool-1-thread-1] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 17401, SQLState: 99999
13 Oct 2015 14:37:52,706 2755614 [pool-1-thread-1] ERROR org.hibernate.util.JDBCExceptionReporter - Protocol violation: [6, 7, 0]
13 Oct 2015 14:37:52,706 2755614 [pool-1-thread-1] INFO org.hibernate.event.def.DefaultLoadEventListener - Error performing load command
org.hibernate.exception.GenericJDBCException: could not load an entity: [snbts.proteus.dataaccess.IntegrationQueue#2]
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1799)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:47)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:41)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:2730)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:365)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:346)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:123)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:82)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:862)
at org.hibernate.impl.SessionImpl.immediateLoad(SessionImpl.java:820)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:62)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:98)
at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:158)
at snbts.proteus.dataaccess.IntegrationQueue$$EnhancerByCGLIB$$14c8fbf7.setStatus(<generated>)
at snbts.proteus.integrationengine.IntegrationThread.setStatus(IntegrationThread.java:109)
at snbts.proteus.integrationengine.IntegrationThread.run(IntegrationThread.java:48)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.sql.SQLException: Protocol violation: [6, 7, 0]
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:464)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1044)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1199)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1289)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3584)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3628)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1493)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:139)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1669)
at org.hibernate.loader.Loader.doQuery(Loader.java:662)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1785)
... 24 more
13 Oct 2015 14:37:52,706 2755614 [pool-1-thread-1] ERROR snbts.proteus.integrationengine.IntegrationThread - Problem updating database: could not load an entity: [snbts.proteus.dataaccess.IntegrationQueue#2]
13 Oct 2015 14:37:54,752 2757660 [pool-1-thread-1] WARN com.mchange.v2.c3p0.impl.NewPooledConnection - [c3p0] A PooledConnection that has already signalled a Connection error is still in use!
13 Oct 2015 14:37:54,752 2757660 [pool-1-thread-1] WARN com.mchange.v2.c3p0.impl.NewPooledConnection - [c3p0] Another error has occurred [ java.sql.SQLException: Protocol violation ] which will not be reported to listeners!
java.sql.SQLException: Protocol violation
at oracle.jdbc.driver.T4CTTIiov.unmarshalV10(T4CTTIiov.java:210)
at oracle.jdbc.driver.T4C8Oall.readIOV(T4C8Oall.java:592)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:325)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:884)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1167)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1289)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3584)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3628)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1493)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:139)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1669)
at org.hibernate.loader.Loader.doQuery(Loader.java:662)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1785)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:47)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:41)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:2730)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:365)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:346)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:123)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:82)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:862)
at org.hibernate.impl.SessionImpl.immediateLoad(SessionImpl.java:820)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:62)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:98)
at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:158)
at snbts.proteus.dataaccess.IntegrationQueue$$EnhancerByCGLIB$$14c8fbf7.toString(<generated>)
at java.util.Formatter$FormatSpecifier.printString(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.lang.String.format(Unknown Source)
at snbts.proteus.integrationengine.queue.QueueItem.build(QueueItem.java:72)
at snbts.proteus.integrationengine.IntegrationThread.processIntegrationQueue(IntegrationThread.java:58)
at snbts.proteus.integrationengine.IntegrationThread.run(IntegrationThread.java:49)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Versions we are using:
Java 6
Hibernate 3.1.3
ojdbc6 11.2.0.4.0
Oracle 10g EE 10.2.0.5.0 64bit
Method attempting to load the entity:
private boolean setStatus(final String status) {
LOGGER.trace(String.format("Setting status to: %s on %s", status, integrationQueue.getDescription()));
boolean hasDbConnection = true;
try {
final Session session = CustomSessionFactory.getSessionFactory().getSession();
session.beginTransaction();
LOGGER.trace(CustomSessionFactory.TRANSACTION_BEGUN);
this.integrationQueue = (IntegrationQueue)session.load(IntegrationQueue.class, integrationQueue.getId());
integrationQueue.setStatus(status);
session.update(integrationQueue);
session.flush();
LOGGER.trace(String.format("Session Object Update: Integration Queue %d", integrationQueue.getId()));
session.getTransaction().commit();
LOGGER.trace(CustomSessionFactory.TRANSACTION_COMMITTED);
LOGGER.trace(String.format("Status set to: %s on %s", status, integrationQueue.getDescription()));
} catch (org.hibernate.exception.JDBCConnectionException e) {
LOGGER.error(String.format("Database Connection Problem: %s", e.getMessage()));
CustomSessionFactory.getSessionFactory().removeSession();
hasDbConnection = false;
} catch (GenericJDBCException e) {
LOGGER.error(String.format("Problem updating database: %s", e.getMessage()));
}
return hasDbConnection;
Entity:
public class IntegrationQueue implements Serializable {
public static final String STATUS_SHUTDOWN = "Shutdown";
public static final String STATUS_ACTIVE = "Active";
public static final String STATUS_IDLE = "Idle";
public static final String STATUS_ERROR_WC = "Error - Wrong Configuration";
private long id;
private String description;
private String status;
private IntegrationEngine integrationEngine;
public IntegrationQueue() {
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
public IntegrationEngine getIntegrationEngine() {
return integrationEngine;
}
public void setIntegrationEngine(final IntegrationEngine integrationEngine) {
this.integrationEngine = integrationEngine;
}
public String getStatus() {
return status;
}
public void setStatus(final String status) {
this.status = status;
}
public String toString(){
return String.format("Integration Queue: %d - %s", id, status);
}
}
HBM File:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="snbts.proteus.dataaccess.IntegrationQueue" table="INTEGRATIONQUEUE">
<id name="id" type="long" column="INTEGRATIONQUEUE_ID">
<generator class="assigned"/>
</id>
<property name="description" type="string" column="DESCRIPTION">
<meta attribute="field-description">
The description of the record.
</meta>
</property>
<property name="status" type="string" column="STATUS">
<meta attribute="field-description">
The status of the record.
</meta>
</property>
<many-to-one name="integrationEngine" class="snbts.proteus.dataaccess.IntegrationEngine"
column="INTEGRATIONENGINE_ID" not-null="true"/>
</class>
</hibernate-mapping>
I have spent a few hours trying to set up my first Hibernate application and it still doesn't work.
I have WAMP Server with my MySQL Data Base called "hibernatetest". I have Project in Eclipse, which contains Hibernate library, and mysql-connector-java-5.1.18-bin.jar. I have also this classes:
HibernateUtil.java:
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory(
new StandardServiceRegistryBuilder().build() );
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
test.java (contains main):
import org.hibernate.Session;
import templates.Album;
public class test {
public static void main(String[] args){
Album i = new Album();
i.setID(1);
i.setArtist("Iron Maiden");
i.setTitle("The Book of Souls");
i.setLabel("Warner Music");
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(i);
session.getTransaction().commit();
session.close();
System.out.println("Saved");
}
}
Album.java:
package templates;
public class Album {
private int ID;
private String title;
private String artist;
private String label;
public Album(){
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
Album.hbm.xml: link
Hibernate.cfg.xml: link
StackTrace:
wrz 15, 2015 10:04:47 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.1.Final}
wrz 15, 2015 10:04:47 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
wrz 15, 2015 10:04:47 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
wrz 15, 2015 10:04:47 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.
wrz 15, 2015 10:04:48 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.0.Final}
wrz 15, 2015 10:04:49 PM org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator initiateService
WARN: HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections
wrz 15, 2015 10:04:49 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata : The application must supply JDBC connections
Initial SessionFactory creation failed.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Exception in thread "main" java.lang.ExceptionInInitializerError
at HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
at HibernateUtil.<clinit>(HibernateUtil.java:7)
at test.main(test.java:13)
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:244)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
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:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
at HibernateUtil.buildSessionFactory(HibernateUtil.java:12)
... 2 more
Caused by: 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:234)
... 15 more
What am I doing wrong?
As the error says, you need to specify the dialect in your hibernate.cfg file.
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
I had the same problem . just add your port number after localhost .in my case it is localhost:3306
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_db</property>
This is how I fixed my error.
My environment is same as yours Hibernate 5+, Mysql & WAMP Server
Make sure you include jta jar which is included at this location \hibernate-release-5.0.5.Final\lib\osgi
You should add new user and grant all privileges. And the HOST should be localhost
And your hibernate.cfg.xml should look like this
Thats how it worked for me. I figured I had to give localhost and NOT %
I noticed some things that may be causing the trouble:
1) In your hibernate.cfg.xml you are not specifying the password for your connection. You can do so by adding the <property name="connection.password">your_Pass_here</property> property (or did you ommit it for privacy reasons?)
2) as #Prerak Tiwari mentioned, you are not specifying the Dialect. Do so as he mentioned with the <property name="dialect">org.hibernate.dialect.MySQLDialect</property> property
3) I notice that the name of you properties is different as the ones most people use. Instead of adding ...name="hibernate.connection.driver_class"... ommit the hibernate. part, so it should look like this:
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernatetest</property>
<property name="connection.username">root</property>
Your password property here...
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="/templates/Album.hbm.xml"/>
</session-factory>
Hope some of this works for you :)
Check for passwor is correct or not in hibernate.cfg.xml
<property name="connection.password">root</property>
I'am learning to use java since few weeks et i want to use Hibernate in simple Java console application.
I download the last version of Hibernate ORM (4.3.8)
I add this Jars in my ClassPath :
com.mysql.jdbc_5.1.5.jar
sqlite-jdbc-3.8.7.jar
Hibernate Library\antlr-2.7.7.jar
Hibernate Library\dom4j-1.6.1.jar
Hibernate Library\hibernate-commons-annotations-4.0.5.Final.jar
Hibernate Library\hibernate-core-4.3.8.Final.jar
Hibernate Library\hibernate-jpa-2.1-api-1.0.0.Final.jar
Hibernate Library\jandex-1.1.0.Final.jar
Hibernate Library\javassist-3.18.1-GA.jar
Hibernate Library\jboss-logging-3.1.3.GA.jar
Hibernate Library\jboss-logging-annotations-1.2.0.Beta1.jar
Hibernate Library\jboss-transaction-api_1.2_spec-1.0.0.Final.jar
My Class :
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENT_INFORMATIONS")
public class Student_Info {
#Id
private int rollNo;
private String name;
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My Main Code :
Student_Info student = new Student_Info();
student.setName("Fabien");
student.setRollNo(1);
SessionFactory sessionFactory;
ServiceRegistry serviceRegistry;
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(student);
session.getTransaction().commit();
session.close();
sessionFactory.close();
SQLite
First i create an hibernate.cfg.xml configuration for SQLite with dialect property to "util.SQLiteDialect"
<?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="show_sql">true</property>
<property name="format_sql">true</property>
<property name="dialect">util.SQLiteDialect</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="connection.url">jdbc:sqlite:SQLiteJDBC.sqlite</property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<!-- create / update -->
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- Liste des classes à Mapper en base de données -->
<!-- <mapping resource="User.hbm.xml"/> -->
<mapping class="com.hibernate.Student_Info"/>
</session-factory>
</hibernate-configuration>
When i run my main program i have this error :
...
INFO: HHH000006: Autocommit mode: false
janv. 10, 2015 4:23:40 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Exception in thread "main" org.hibernate.boot.registry.selector.spi.StrategySele
ctionException: Unable to resolve name [util.SQLiteDialect] as strategy [org.hib
ernate.dialect.Dialect]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStr
ategyImplementor(StrategySelectorImpl.java:128)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDe
faultableStrategy(StrategySelectorImpl.java:155)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveSt
rategy(StrategySelectorImpl.java:136)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDiale
ct(DialectFactoryImpl.java:78)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(D
ialectFactoryImpl.java:68)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesIm
pl.java:165)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureSe
rvice(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService
(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(Abstra
ctServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:18
87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at com.hibernate.Main.main(Main.java:26)
MySql
After i tried with a mysql Database
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/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/hierbnate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<!-- JDBC Connection pool -->
<property name="connection.pool_size">1</property>
<!-- SQL Dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_cass">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- create / update -->
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- Liste des classes à Mapper en base de données -->
<!-- <mapping resource="User.hbm.xml"/> -->
<mapping class="com.hibernate.Student_Info"/>
</session-factory>
</hibernate-configuration>
When i run my main programm i have this error :
...
janv. 10, 2015 4:41:43 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://local
host:3306/hierbnate]
janv. 10, 2015 4:41:43 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
janv. 10, 2015 4:41:43 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
janv. 10, 2015 4:41:43 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Error ca
lling Driver#connect
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLState
ConversionDelegate.java:123)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.co
nvert(BasicConnectionCreator.java:118)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.conver
tSqlException(BasicConnectionCreator.java:140)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeC
onnection(DriverConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.create
Connection(BasicConnectionCreator.java:75)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProvid
erImpl.configure(DriverManagerConnectionProviderImpl.java:106)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureSe
rvice(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService
(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(Abstra
ctServiceRegistryImpl.java:206)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAcces
s(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesIm
pl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureSe
rvice(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService
(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(Abstra
ctServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:18
87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at com.hibernate.Main.main(Main.java:25)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown da
tabase 'hierbnate'
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:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1031)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:894)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3808)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1256)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2032)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
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:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeC
onnection(DriverConnectionCreator.java:55)
... 13 more
1 - Do you know if is it possible to use hibernate on SQLite ?
2 - If yes, do you know why it doesn't works ?
3 - For MySql, what is the problem ?
thank you very much !!
Thanks to Todd for my Syntaxe Error (MySql).
For SQLite, the dialect is not present in hibernate 4.3. So i found and adapt a classe for use SQLite with Hibernate 4.3.8 :
/*
* The author disclaims copyright to this source code. In place of
* a legal notice, here is a blessing:
*
* May you do good and not evil.
* May you find forgiveness for yourself and forgive others.
* May you share freely, never taking more than you give.
*
*/
package org.hibernate.dialect;
import java.sql.Types;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.Hibernate;
public class SQLiteDialect extends Dialect {
public SQLiteDialect() {
registerColumnType(Types.BIT, "integer");
registerColumnType(Types.TINYINT, "tinyint");
registerColumnType(Types.SMALLINT, "smallint");
registerColumnType(Types.INTEGER, "integer");
registerColumnType(Types.BIGINT, "bigint");
registerColumnType(Types.FLOAT, "float");
registerColumnType(Types.REAL, "real");
registerColumnType(Types.DOUBLE, "double");
registerColumnType(Types.NUMERIC, "numeric");
registerColumnType(Types.DECIMAL, "decimal");
registerColumnType(Types.CHAR, "char");
registerColumnType(Types.VARCHAR, "varchar");
registerColumnType(Types.LONGVARCHAR, "longvarchar");
registerColumnType(Types.DATE, "date");
registerColumnType(Types.TIME, "time");
registerColumnType(Types.TIMESTAMP, "timestamp");
registerColumnType(Types.BINARY, "blob");
registerColumnType(Types.VARBINARY, "blob");
registerColumnType(Types.LONGVARBINARY, "blob");
// registerColumnType(Types.NULL, "null");
registerColumnType(Types.BLOB, "blob");
registerColumnType(Types.CLOB, "clob");
registerColumnType(Types.BOOLEAN, "integer");
registerFunction( "concat", new VarArgsSQLFunction(StringType.INSTANCE, "", "||", "") );
registerFunction( "mod", new SQLFunctionTemplate( IntegerType.INSTANCE, "?1 % ?2" ) );
registerFunction( "substr", new StandardSQLFunction("substr", StringType.INSTANCE) );
registerFunction( "substring", new StandardSQLFunction( "substr", StringType.INSTANCE ) );
}
public boolean supportsIdentityColumns() {
return true;
}
/*
public boolean supportsInsertSelectIdentity() {
return true; // As specify in NHibernate dialect
}
*/
public boolean hasDataTypeInIdentityColumn() {
return false; // As specify in NHibernate dialect
}
/*
public String appendIdentitySelectToInsert(String insertString) {
return new StringBuffer(insertString.length()+30). // As specify in NHibernate dialect
append(insertString).
append("; ").append(getIdentitySelectString()).
toString();
}
*/
public String getIdentityColumnString() {
// return "integer primary key autoincrement";
return "integer";
}
public String getIdentitySelectString() {
return "select last_insert_rowid()";
}
public boolean supportsLimit() {
return true;
}
protected String getLimitString(String query, boolean hasOffset) {
return new StringBuffer(query.length()+20).
append(query).
append(hasOffset ? " limit ? offset ?" : " limit ?").
toString();
}
public boolean supportsTemporaryTables() {
return true;
}
public String getCreateTemporaryTableString() {
return "create temporary table if not exists";
}
public boolean dropTemporaryTableAfterUse() {
return false;
}
public boolean supportsCurrentTimestampSelection() {
return true;
}
public boolean isCurrentTimestampSelectStringCallable() {
return false;
}
public String getCurrentTimestampSelectString() {
return "select current_timestamp";
}
public boolean supportsUnionAll() {
return true;
}
public boolean hasAlterTable() {
return false; // As specify in NHibernate dialect
}
public boolean dropConstraints() {
return false;
}
public String getAddColumnString() {
return "add column";
}
public String getForUpdateString() {
return "";
}
public boolean supportsOuterJoinForUpdate() {
return false;
}
public String getDropForeignKeyString() {
throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect");
}
public String getAddForeignKeyConstraintString(String constraintName,
String[] foreignKey, String referencedTable, String[] primaryKey,
boolean referencesPrimaryKey) {
throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect");
}
public String getAddPrimaryKeyConstraintString(String constraintName) {
throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect");
}
public boolean supportsIfExistsBeforeTableName() {
return true;
}
public boolean supportsCascadeDelete() {
return false;
}
#Override
public boolean bindLimitParametersInReverseOrder() {
return true;
}
}
I think you might have just spelled "hibernate" wrong...
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'hierbnate'
Try changing this:
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hierbnate</property>
To this:
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
(Unless your db is really called hierbnate, and then I'll just delete this answer).