I am eclipse IDE..
I have configured hibernate properly but still i am getting this error.
Directory Structure:
HibernateProject-Java Resources-Src
-com.project -Employeee.java -Testjdbc.java(contains main function)
-hibernate.cfg.xml
Employee.java
package com.package;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employeee")
public class Employeee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="Empcode")
private int Empcode;
#Column(name="EmpName")
private String EmpName;
#Column(name="EmpDesignation")
private String EmpDesignation;
#Column(name="EmpDOB")
private Date EmpDOB;
#Column(name="EmpJOD")
private Date EmpJOD;
#Column(name="EmpAge")
private int EmpAge;
#Column(name="EmpBasic_Pay")
private double EmpBasic_Pay;
public int getEmpcode() {
return Empcode;
}
public void setEmpcode(int empcode) {
Empcode = empcode;
}
public String getEmpName() {
return EmpName;
}
public void setEmpName(String empName) {
EmpName = empName;
}
public String getEmpDesignation() {
return EmpDesignation;
}
public void setEmpDesignation(String empDesignation) {
EmpDesignation = empDesignation;
}
public Date getEmpDOB() {
return EmpDOB;
}
public void setEmpDOB(Date empDOB) {
EmpDOB = empDOB;
}
public Date getEmpJOD() {
return EmpJOD;
}
public void setEmpJOD(Date empJOD) {
EmpJOD = empJOD;
}
public int getEmpAge() {
return EmpAge;
}
public void setEmpAge(int empAge) {
EmpAge = empAge;
}
public double getEmpBasic_Pay() {
return EmpBasic_Pay;
}
public void setEmpBasic_Pay(double empBasic_Pay) {
EmpBasic_Pay = empBasic_Pay;
}
public Employeee() {
}
public Employeee(int empcode, String empName, String empDesignation, java.util.Date sdate, java.util.Date edate, int empAge,
double empBasic_Pay) {
super();
Empcode = empcode;
EmpName = empName;
EmpDesignation = empDesignation;
EmpDOB = sdate;
EmpJOD = edate;
EmpAge = empAge;
EmpBasic_Pay = empBasic_Pay;
}
#Override
public String toString() {
return "Student [Empcode=" + Empcode + ", EmpName=" + EmpName + ", EmpDesignation=" + EmpDesignation
+ ", EmpDOB=" + EmpDOB + ", EmpJOD=" + EmpJOD + ", EmpAge=" + EmpAge + ", EmpBasic_Pay=" + EmpBasic_Pay
+ "]";
}
}
Testjdbc.java
package com.package;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.wipro.Employeee;
public class TestJDBC {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Employeee.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// create a student object
System.out.println("Creating new student object...");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
java.util.Date sdate=sdf.parse("2018/07/22");
java.util.Date edate=sdf.parse("2019/07/22");
//empcode empName empDesignation empDOB empJOD empAge empBasic_Pay;
Employeee emp=new Employeee(101,"ABC","Engineer",sdate,edate,25,250000.00);
// start a transaction
session.beginTransaction();
// save the student object
System.out.println("Saving the student...");
session.save(emp);
// commit transaction
session.getTransaction().commit();
System.out.println("Done!");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
factory.close();
}
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/jdbcassignment?useSSL=false&serverTimezone=UTC</property>
<property name="connection.username">root</property>
<property name="connection.password">tiger</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Error:
Aug 25, 2018 6:13:07 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.3.1.Final}
Aug 25, 2018 6:13:07 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Aug 25, 2018 6:13:07 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.3.Final}
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/jdbcassignment?useSSL=false&serverTimezone=UTC]
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata : null
Aug 25, 2018 6:13:07 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl makeLobCreatorBuilder
INFO: HHH000422: Disabling contextual LOB creation as connection was null
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 08001
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Public Key Retrieval is not allowed
Exception in thread "main" 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:275)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:179)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:119)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:84)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:474)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:85)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:689)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at com.wipro.TestJDBC.main(TestJDBC.java:23)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:48)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:118)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.addConnections(DriverManagerConnectionProviderImpl.java:363)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:282)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:260)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections$Builder.build(DriverManagerConnectionProviderImpl.java:401)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:112)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:75)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:100)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:246)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
... 14 more
Caused by: java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:110)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:832)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 29 more
Please see if you can help.
Related
I would like to build a small console application executed by tests just of learning Hibernate purposes. Unfortunately, hibernate returns with no data and when a list should be populated by the entities it throws outofindex exception. I assume due to no result coming back. I have been reading the tutorials and questions here, but I cannot find why this happens.
JDBC connection is working well, it is copied from DataGrip.
What other detailed should be checked more? Sorry, I'm totally inexperienced in this world.
Please find the code below.
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL95Dialect</property>
<property name="connection.url" >jdbc:postgresql://localhost:5432/digitallibraryreports</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.username">postgres</property>
<property name="connection.password">postgres</property>
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
Source:
public class ETL {
private static SessionFactory factory;
public ETL(){
try{
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex){
System.err.println("Failed to create sessionfactory" + ex);
throw new ExceptionInInitializerError(ex);
}
}
public SessionFactory getSessionFactory() {
return factory;
}
}
Class fetching stuff:
public class FeatureFetcher {
private static SessionFactory sessionFactory;
public FeatureFetcher() {
ETL etl = new ETL();
sessionFactory = etl.getSessionFactory();
}
public void fetchFeatures() {
Session session = sessionFactory.openSession();
EntityManager em = sessionFactory.createEntityManager();
try {
em.getTransaction().begin();
List<Test> testEntityList = em.createQuery("FROM Test", Test.class).getResultList();
if (testEntityList.size() > 0) {
for (Iterator<Test> iterator = testEntityList.iterator(); iterator.hasNext(); ) {
Test testEntity = (Test) iterator.next();
System.out.println("Test Entity name: " + testEntity.getName());
System.out.println("Test Entity id: " + testEntity.getId());
}
em.getTransaction().commit();
em.close();
}
} catch (HibernateException e) {
em.getTransaction().rollback();
e.printStackTrace();
} finally {
em.close();
}
}
}
Entity:
#Entity
#Table(name = "test", schema = "public")
public class Test {
#javax.persistence.Id
#GeneratedValue
#Column(name = "id")
public Integer Id;
#Column(name = "name")
public String Name;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
SQL:
CREATE TABLE public.TEST
(
Id INT PRIMARY KEY,
Name VARCHAR(255)
);
Logs:
May 14, 2017 9:20:30 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
May 14, 2017 9:20:30 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 14, 2017 9:20:31 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/digitallibraryreports]
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
May 14, 2017 9:20:31 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL95Dialect
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
May 14, 2017 9:20:31 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#6253c26
May 14, 2017 9:20:31 PM org.hibernate.hql.internal.QuerySplitter concreteQueries
WARN: HHH000183: no persistent classes found for query class: FROM Test
May 14, 2017 9:20:31 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
You need to register entites in the SessionFactory.
You can do it by editing hibernate.cfg.xml by this way:
<session-factory>
...
<mapping class="some.pack.Test" />
...
</session-factory>
You can use Spring to scan a package to add entites, as well. Or, for testing purposes, EntityScanner from here.
Appart that, remove all lines related to the EntityManager and use Session. Remove this:
EntityManager em = sessionFactory.createEntityManager();
Hibernate SessionFactory is not aware of the your entity. You need to add the following resource to the hibernate.cfg.xml file inside the tag replacing the Entity with the correct name of the hbm.xml file.
<session-factory>
.
.
.
<mapping resource="Entity.hbm.xml"/>
</session-factory>
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;
.....
}
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 new to Hibernate.
I am using NetBeans 7.4 , Hibernate 4.3.6 and Database as Ms Sql Server.
It works fine for fetching data from database but it gives error for Insert , Update , Delete.
My Hibernate Configuration file as :
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://SqlSer:1433;databaseName=HibSample</property>
<property name="hibernate.connection.username">SA</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="Entity/Sample.hbm.xml"/>
</session-factory>
</hibernate-configuration>
my HibernateUtil File is as:
public class NewHibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
My Reverse Engineering File as:
<hibernate-reverse-engineering>
<schema-selection match-catalog="HibSample" match-schema="dbo"/>
<table-filter match-name="Sample"/>
</hibernate-reverse-engineering>
My Pojo and Mapping Files are :
public class Sample implements java.io.Serializable {
private int id;
private String fullName;
private String address;
public Sample() {
}
public Sample(int id, String fullName) {
this.id = id;
this.fullName = fullName;
}
public Sample(int id, String fullName, String address) {
this.id = id;
this.fullName = fullName;
this.address = address;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
}
and
<hibernate-mapping>
<class name="Entity.Sample" table="Sample" schema="dbo" catalog="HibSample">
<id name="id" type="int">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="fullName" type="string">
<column name="FullName" length="50" not-null="true" />
</property>
<property name="address" type="string">
<column name="Address" length="50" />
</property>
</class>
</hibernate-mapping>
Main File is :
public class Main
{
public Main(){};
public static void main(String args[])
{
Session session = NewHibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Sample s = new Sample();
s.setId(3);
s.setFullName("Demo");
s.setAddress("Demo");
Sample s1 = (Sample)session.load(Sample.class, 2);
System.out.println("ID :"+s1.getId());
System.out.println("Full Name : "+s1.getFullName());
System.out.println("Address : "+s1.getAddress());
session.save(s);
if(!tx.wasCommitted())
{
tx.commit();
}
}catch(Exception ex)
{
if(tx != null)
{
tx.rollback();
ex.printStackTrace();
}
}finally{
session.close();
}
System.exit(0);
}
}
Table Data are as follow :
ID Full Name Address
1 XYZ India
2 ABC India
Error IS :
Dec 17, 2014 4:42:42 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Dec 17, 2014 4:42:42 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.6.Final}
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Dec 17, 2014 4:42:42 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: Entity/Demo.hbm.xml
Dec 17, 2014 4:42:42 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: Entity/Sample.hbm.xml
Dec 17, 2014 4:42:42 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Dec 17, 2014 4:42:42 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://150.10.10.233;databaseName=HibSample]
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=SA, password=****}
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Dec 17, 2014 4:42:43 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect
Dec 17, 2014 4:42:43 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Dec 17, 2014 4:42:43 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Result
ID :2
Full Name : ABC
Address : India
Hibernate: insert into HibSample.dbo.Sample (FullName, Address, ID) values (?, ?, ?)
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: -1; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:81)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:73)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:63)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at UI.Main.main(Main.java:45)
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
BUILD SUCCESSFUL (total time: 1 second)
I have search all possibilities but can't find the solution.