When I want to create a one to one mapping by using hibernate, the error "Could not execute JDBC batch update" keeps raising and I noticed that it was caused by the failure of creating tables in the MySQL according to the error it showed. Would you please help me to find out the problems inside it? Thank you!
Hibernate Configuration 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>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost/june13?serverTimezone=UTC</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<mapping resource="Emp-hbm.xml"/>
</session-factory>
</hibernate-configuration>
Hibernate one-to-one mapping file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.hibernate.one2one.Emp" table="emp_906">
<id name="id" column="emp_id"></id>
<property name="name" column="emp_name" />
<one-to-one name="phoneno" cascade="all"></one-to-one>
</class>
<class name="com.hibernate.one2one.PhoneNumber" table="phone_906">
<id name="pid"></id>
<property name="network" />
<property name="phonenumber" />
<one-to-one name="emp"></one-to-one>
</class>
</hibernate-mapping>
Main File:
package com.hibernate.one2one;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class App
{
public static void main(String[] args)
{
Configuration cfg=new Configuration();
cfg.configure("Hibernate-cfg.xml");
System.out.println("Configuration Object Created Successfully");
SessionFactory sf=cfg.buildSessionFactory();
System.out.println("Session Factory Object is Created");
Session s=sf.openSession();
Transaction t=s.beginTransaction();
Emp e=new Emp();
e.setId(104);
e.setName("Lee Meng");
PhoneNumber ph = new PhoneNumber();
ph.setPid(201);
ph.setNetwork("ATT");
ph.setPhonenumber("9900336611");
e.setPhoneno(ph);
ph.setEmp(e);
s.persist(e);
t.commit();
s.close();
sf.close();
}
}
The error code:
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:114)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:109)
at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:244)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2411)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2874)
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.hibernate.one2one.App.main(App.java:32)
Caused by: java.sql.BatchUpdateException: Table 'june13.emp_906' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.cj.util.Util.handleNewInstance(Util.java:192)
at com.mysql.cj.util.Util.getInstance(Util.java:167)
at com.mysql.cj.util.Util.getInstance(Util.java:174)
at com.mysql.cj.jdbc.exceptions.SQLError.createBatchUpdateException(SQLError.java:224)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeBatchSerially(ClientPreparedStatement.java:853)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeBatchInternal(ClientPreparedStatement.java:435)
at com.mysql.cj.jdbc.StatementImpl.executeBatch(StatementImpl.java:796)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 15 more
Caused by: java.sql.SQLSyntaxErrorException: Table 'june13.emp_906' doesn't exist
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
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.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeBatchSerially(ClientPreparedStatement.java:832)
... 19 more
How about adding <property name="hbm2ddl.auto" value="create"/> to your hibernate configruation file. This will ensure your tables are created on startup and leave them intact.
validate: validate the schema, makes no changes to the database.
update: update the schema. create: creates the schema, destroying
previous data. create-drop: drop the schema when the SessionFactory is
closed explicitly, typically when the application is stopped. none:
does nothing with the schema, makes no changes to the database
A more extensive description of the possible values :
What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do
It is a java error: Please disable/comment out recovery part from MySQL my.cnf file.
As now the MySQL is in a state where users cannot change/edit anything on the MySQL database.
Related
I am new to Hibernate and I am learning myself. I've got a problem when I am executing a program. I have tried a lot to solve the error but got no luck. Here is my main and configuration file and hbm files.
package com.HibernateLearn;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Client {
public static void main(String[] args) {
// creating configuration object
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");// populates the data of the
// configuration file
// creating seession factory object
SessionFactory factory = cfg.buildSessionFactory();
// creating session object
Session session = factory.openSession();
// creating transaction object
Transaction t = session.beginTransaction();
Employee e1 = new Employee();
e1.setId(103);
e1.setF_name("Ahammed");
e1.setL_name("Naseer");
//e1.getId();
//e1.getF_name();
e1.getL_name();
session.persist(e1);// persisting the object
t.commit();// transaction is committed
session.close();
System.out.println("successfully saved");
}
}
my hibernate.cfg.xml
<?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="hbm2ddl.auto">create-update</property> -->
<!--Below are other values for hbm2ddl.auto validate: validate the schema,
makes no changes to the database. update: update the schema. create: creates
the schema, destroying previous data. create-drop: drop the schema at the
end of the session. -->
<!--property name="hibernate.cache.use_query_cache">true</property -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/joctopusdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">abc123</property>
<mapping resource="hibernate.hbm.xml"/>
</session-factory>
</hibernate-configuration>
my hibernate.hbm.xml file
<?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="com.HibernateLearn.Employee" table="emp_table">
<id name="Id">
<generator class="increment"></generator>
</id>
<property name="F_name"></property>
<property name="L_name"></property>
</class>
</hibernate-mapping>
Error I am getting
Exception in thread "main" org.hibernate.PersistentObjectException: detached entity passed to persist: com.HibernateLearn.Employee
You do e1.setId(103); while the unique ids for new entities are generated for you:
<id name="Id">
<generator class="increment"></generator>
</id>
Hibernate is expecting your Employee instance is already in the database because it has its id set. In other words, Hibernate is expecting it is updating an existing instance that is attached to the session. Hence the detached error message.
So to fix this you should not set the id for new entities yourself.
I am facing a strange problem. I am using hibernate and trying to run a sample DB updation code using Hibernate framework. I am using MySQL database #localhost:3306. The name of the schema is "hibernate_test".
I have created a table named as "employee_details" with the below columns:
EmployeeID, FirstName, SecondName.
Below is the configuration #hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name = "hbm2ddl.auto">create</property>
<property name = "dialect">org.hibernate.dialect.MySQLDialect</property>
<property name = "connection.url">jdbc:mysql://localhost:3306/hibernate_test"</property>
<property name = "connection.username">root</property>
<property name = "connection.password">mysql123</property>
<property name = "connection.driver_class">com.mysql.jdbc.Driver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
This is my hibernate-mapping code :
<hibernate-mapping>
<class name = "com.somnath.test.Employee" table = "employee_details">
<id name = "employeeID">
<generator class ="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
I am getting the below error while running the application:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'hibernate_test"'
I am not sure where I am doing wrong. As I have searched many similar problems regarding the issue, but yet to get any valid solution.
There's a " in your database name; at the end of your database name. Remove that and it should work.
configuration.cfg.xml
<!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>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate_xml</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="format_sql">true</property>
<!-- mapping configurations -->
<mapping resource="resources/Employee.hbm.xml" />
<mapping resource="resources/Department.hbm.xml" />
</session-factory>
</hibernate-configuration>
Here is my Employee.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.domain.Employee" table="employee">
<id name="id" type="long" column="id">
<generator class="increment" />
</id>
<property name="firstName" name="firstName" />
<property name="salary" name="salary" />
<many-to-one name="department" class="com.domain.Department">
<column name="department" />
</many-to-one>
</class>
</hibernate-mapping>
department.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.domain.Department" table="department">
<id name="id" type="long" column="id">
<generator class="auto" />
</id>
<property name="deptName" column="deptName" />
</class>
</hibernate-mapping>
session Factory
public static SessionFactory getSessionFactory() {
SessionFactory sessionFactory = null;
try {
sessionFactory = new Configuration().configure("resources/configuration.cfg.xml")
.addResource("resources/Employee.hbm.xml").addResource("resources/Department.hbm.xml")
.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
return sessionFactory;
}
and finally exception
Exception in thread "main" java.lang.ExceptionInInitializerError at
com.utility.HibernateUtil.getSessionFactory(HibernateUtil.java:15) at
com.client.Client.getTransaction(Client.java:13) at
com.client.Client.main(Client.java:32) Caused by:
org.hibernate.boot.InvalidMappingException: Could not parse mapping
document: resources/Employee.hbm.xml (RESOURCE) at
org.hibernate.boot.jaxb.internal.InputStreamXmlSource.doBind(InputStreamXmlSource.java:46)
at
org.hibernate.boot.jaxb.internal.UrlXmlSource.doBind(UrlXmlSource.java:36)
at
org.hibernate.boot.spi.XmlMappingBinderAccess.bind(XmlMappingBinderAccess.java:59)
at
org.hibernate.boot.MetadataSources.addResource(MetadataSources.java:274)
at
org.hibernate.cfg.Configuration.addResource(Configuration.java:498)
at com.utility.HibernateUtil.getSessionFactory(HibernateUtil.java:12)
... 2 more Caused by: org.hibernate.boot.MappingException: Unable to
perform unmarshalling at line number 0 and column 0. Message: null :
origin(resources/Employee.hbm.xml) at
org.hibernate.boot.jaxb.internal.AbstractBinder.jaxb(AbstractBinder.java:177)
at
org.hibernate.boot.jaxb.internal.MappingBinder.doBind(MappingBinder.java:61)
at
org.hibernate.boot.jaxb.internal.AbstractBinder.doBind(AbstractBinder.java:102)
at
org.hibernate.boot.jaxb.internal.AbstractBinder.bind(AbstractBinder.java:57)
at
org.hibernate.boot.jaxb.internal.InputStreamXmlSource.doBind(InputStreamXmlSource.java:43)
... 7 more Caused by: javax.xml.bind.UnmarshalException
- with linked exception: [javax.xml.stream.XMLStreamException: ParseError at [row,col]:[10,49] Message:
http://www.w3.org/TR/1999/REC-xml-names-19990114#AttributeNotUnique?property&name] at
com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:470)
at
com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:448)
at
com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:420)
at
org.hibernate.boot.jaxb.internal.AbstractBinder.jaxb(AbstractBinder.java:171)
... 11 more Caused by: javax.xml.stream.XMLStreamException:
ParseError at [row,col]:[10,49] Message:
http://www.w3.org/TR/1999/REC-xml-names-19990114#AttributeNotUnique?property&name
at
com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:596)
at
com.sun.xml.internal.stream.XMLEventReaderImpl.peek(XMLEventReaderImpl.java:276)
at
javax.xml.stream.util.EventReaderDelegate.peek(EventReaderDelegate.java:104)
at
org.hibernate.boot.jaxb.internal.stax.BufferedXMLEventReader.peek(BufferedXMLEventReader.java:96)
at
javax.xml.stream.util.EventReaderDelegate.peek(EventReaderDelegate.java:104)
at
org.hibernate.boot.jaxb.internal.stax.HbmEventReader.peek(HbmEventReader.java:47)
at
com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.handleCharacters(StAXEventConnector.java:164)
at
com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(StAXEventConnector.java:126)
at
com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:445)
... 13 more
after solving that error I got stuck with other error as
Hibernate:
alter table employee
drop
foreign key FKkxx4wtsgsdt16iix2pso0k126
Sep 27, 2016 3:23:37 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Unable to execute command [
alter table employee
drop
foreign key FKkxx4wtsgsdt16iix2pso0k126]
org.hibernate.tool.schema.spi.CommandAcceptanceException: Unable to execute command [
alter table employee
drop
foreign key FKkxx4wtsgsdt16iix2pso0k126]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:63)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:370)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:355)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applyConstraintDropping(SchemaDropperImpl.java:327)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:229)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:153)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:125)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:111)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:137)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:308)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:483)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:707)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:723)
at com.utility.HibernateUtil.getSessionFactory(HibernateUtil.java:13)
at com.client.Client.getTransaction(Client.java:13)
at com.client.Client.main(Client.java:32)
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'hibernate_xml.employee' doesn't exist
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3206)
at com.mysql.jdbc.Statement.execute(Statement.java:727)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:51)
... 16 more
Hibernate:
drop table if exists department
Hibernate:
drop table if exists employee
Hibernate:
create table department (
id bigint not null,
deptName varchar(255),
primary key (id)
)
Hibernate:
create table employee (
id bigint not null,
firstName varchar(255),
salary double precision,
department bigint,
primary key (id)
)
Hibernate:
alter table employee
add constraint FKkxx4wtsgsdt16iix2pso0k126
foreign key (department)
references department (id)
Sep 27, 2016 3:23:38 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#bd06ca'
department saved with id : 0
Hibernate:
select
max(id)
from
employee
employee saved with id 1
Sep 27, 2016 3:23:39 PM org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance beforeQuery flushing: com.domain.Department]
Exception in thread "main" java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance beforeQuery flushing: com.domain.Department
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:144)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1403)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:473)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3133)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at com.client.Client.getTransaction(Client.java:27)
at com.client.Client.main(Client.java:32)
Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance beforeQuery flushing: com.domain.Department
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:279)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:462)
at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:298)
at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:309)
at org.hibernate.type.TypeHelper.findDirty(TypeHelper.java:296)
at org.hibernate.persister.entity.AbstractEntityPersister.findDirty(AbstractEntityPersister.java:4139)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.dirtyCheck(DefaultFlushEntityEventListener.java:528)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.isUpdateNecessary(DefaultFlushEntityEventListener.java:215)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:142)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:216)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:85)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:38)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1397)
... 10 more
I am not sure why I am getting this error if everything is in place?
Please help
The name attribute in Employee.hbm.xml is already specified(used twice/duplicate), please use the below update code in Employee.hbm.xml:
<property name="firstName" column="firstName"/>
<property name="salary" column="firstName" />
The file name should be Employee.hbm.xml instead of Employee.xml, since it is a mapping file.
You need to use the below code for your second exception:
<property name="hbm2ddl.auto">update</property>
I am getting this Exception
Exception in thread "main" org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at com.jwt.hibernate.SimpleTest.main(SimpleTest.java:13)
Caused by: org.dom4j.DocumentException: www.hibernate.org Nested exception: www.hibernate.org
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
My hibernate.cfg file is
<?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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3006/mydb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="com/jwt/hibernate/student.hbm.xml" />
</session-factory>
</hibernate-configuration>
My Mapping File is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.jwt.hibernate.Student" table="STUDENT">
<id column="ID" name="id" type="int" />
<property column="STUDENT_NAME" name="name" type="string" />
<property column="DEGREE" name="degree" type="string" />
<property column="ROLL" name="roll" type="string" />
<property column="PHONE" name="phone" type="string" />
</class>
</hibernate-mapping>
My Bean class is:
public class Student {
private int id;
private String name;
private String degree;
private String roll;
private String phone;
/** Getters and setters omitted **/
}
My Tester class is:
public class SimpleTest {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Student student = new Student();
student.setName("Gourab");
student.setRoll("101");
student.setPhone("8888");
student.setDegree("B.E");
Transaction tx = session.beginTransaction();
session.save(student);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}
My Folder Structure is
I have added all required jars for connecting to hibernate and mysql(e.g hibernate-core 3.8.9.Final.jar,mysql-connector-java-5.1.12-bin.jar)
But still I am getting the error.
Please Help me out.
Thanks in advance
Full Stack Trace:
Exception in thread "main" org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at com.jwt.hibernate.SimpleTest.main(SimpleTest.java:12)
Caused by: org.dom4j.DocumentException: www.hibernate.org Nested exception: www.hibernate.org
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
... 2 more
My jar files are
Could you try to check your .jar again? I try to execute your project SimpleTest.java with my .jar. It is work. Please take a look
I copied every file from your page as above and created a new project. Please follow the below structure to avoid the above exception.
public class App
{
public static void main( String[] args )
{
System.out.println("Maven + Hibernate + MySQL");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Student st1 = new Student();
st1.setName("srinivas");
st1.setPhone("99");
st1.setRoll("123");
session.save(st1);
session.getTransaction().commit();
}
}
Hibernate can't parse your hibernate.cfg.xml.
hibernate-core-3.6.9.Final.jar has a file with DTD hibernate-core-3.6.9.Final/org/hibernate/hibernate-configuration-3.0.dtd
Check this file inside hibernate-core-3.6.9.Final.jar.
You need to have the same DTD as hibernate-configuration-3.0.dtd has.
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
Looks like you already have it.
May be you have other hibernate-core jar in the class path with other DTD.
I am building my first hibernate application on eclipse and reads in a set of SFTP credentials from an Oracle table because I want to make them configurable and not hard code them. But when I attempt to run the application it will not parse the hibernate.cfg.xml file. I have tried typing in all the config file and not cut and paste and I have tried changing www.hibernate.org/dtd/hibernate-configuration-3.0.dtd in the config file to http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd. Why won't this work?
Here is the console output;
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.HibernateException: Could not parse
configuration: hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at name.of.package.used.retrieve.main(retrieve.java:14)
Caused by: org.dom4j.DocumentException: Connection refused: connect Nested exception:
Connection refused: connect
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
... 2 more
Here is the mapping 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="name.of.package.used.SFTPDetails" table="SFTP_Creds">
<id column="SFTP_HOST" name="sftp_host">
<generator class="assigned" />
</id>
<property column="SFTP_PORT" generated="never" lazy="false"
name="sftp_port" />
<property column="SFTP_USERNAME" generated="never" lazy="false"
name="sftp_username" />
<property column="SFTP_PASSWORD" generated="never" lazy="false"
name="sftp_password" />
<property column="SFTP_HOSTKEY" generated="never" lazy="false"
name="sftp_hostkey" />
</class>
</hibernate-mapping>
This is the hibernate.cfg.xml 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>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:#hostname:1523:TRNG</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="sftpcreds.hbm.xml"/>
</session-factory>
</hibernate-configuration>
My main Java file that I am running the application is;
package name.of.package.used;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.List;
import org.apache.log4j.Logger;
public class retrieve {
public static void main(String args[]) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");// populates the data of the configuration file
// creating seession factory object
SessionFactory factory = cfg.buildSessionFactory();
// creating session object
Session session = factory.openSession();
// creating transaction object
Transaction t = session.beginTransaction();
Query query = session.createQuery("from SFTPCreds");
java.util.List list = query.list();
System.out.println(list);
t.commit();
session.close();
}
}
I am guessing it is your dtd reference: http://hibernate.sourceforge.net/hibernate-mapping
3.0.dtd
This is down and obsolete You should use ttp://www.jboss.org/dtd/hibernate/hibernate-configuration-3.0.dtd
This means the hibernate.dtd cannot be resolved - its resolution is attempted on the server. The dtd is contained in the jars files - see here and here for how to resolve it.
Also try changing the path from: hibernate.org/dtd to hibernate.sourceforge.net
it means that the XML parser is having a problem trying to access your DTD definition. So first thing to do is to see if you can browse the url for it directly and also check your proxy settings. In my case, I changed it
from
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
to
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
I think you can also try using "http://www.jboss.org/dtd/hibernate/hibernate-configuration-3.0.dtd". It seems like hibernate.org fwds to the jboss location anyways.