Hibernate : unable to map mapping document as they are already available in - java

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>

Related

hibernate: Could not execute JDBC batch update

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.

Hibernate creates multiple foreign keys in database tables for bidirectional associations

I want to create the following tables with the necessary associations accordingly:
However, it seems that I have miyed up something because when Hibernate creates the tables multiple foreign keys are created as shown below:
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess
[org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#5e5595f3]
for (non-JTA) DDL execution was not in auto-commit mode; the
Connection 'local transaction' will be committed and the Connection
will be set into auto-commit mode.
Hibernate: create table APP.ITEMS (ITEM_ID integer generated by
default as identity, NAME varchar(100), NET_PRICE integer, VAT_RATE
integer, CATEGORY_ID integer not null, primary key (ITEM_ID))
Hibernate: create table APP.LIMIT (LIMIT_ID integer not null,
LIMIT_VALUE integer, primary key (LIMIT_ID))
Hibernate: create table APP.PARTNER (PARTNER_ID integer generated by
default as identity, PARTNER_NAME varchar(100), primary key
(PARTNER_ID))
Hibernate: create table APP.TRANSACTIONS (TRANSACTIONS_ID integer
generated by default as identity, FLOW integer not null, NET_PRICE
integer, ITEM_ID integer not null, advicenote integer, ADVICENOTE_ID
integer not null, primary key (TRANSACTIONS_ID))
Hibernate: alter table APP.TRANSACTIONS add constraint
UK_r7btjtpy72nugbhuia8y0xnk6 unique (ITEM_ID)
Hibernate: alter table APP.ADVICENOTE add constraint
FK4n4r6ej5i983gk8fqj20jl899 foreign key (partner) references
APP.PARTNER
Hibernate: alter table APP.ADVICENOTE add constraint
FKr96drd4j6pds8vocvsstcd2a2 foreign key (PARTNER_ID) references
APP.PARTNER
Hibernate: alter table APP.ITEMS add constraint
FKbbkng91eiiqu522okqq0nq7pm foreign key (CATEGORY_ID) references
APP.CATEGORIES
Hibernate: alter table APP.TRANSACTIONS add constraint
FK13kk35nfl3iff7f2cs8er8w0s foreign key (advicenote) references
APP.ADVICENOTE
Hibernate: alter table APP.TRANSACTIONS add constraint
FK8ilbnqyk8lemxj0yvbqm3p7tt foreign key (ITEM_ID) references APP.ITEMS
Hibernate: alter table APP.TRANSACTIONS add constraint
FKqrbn7tojjjkjyusy98a300btp foreign key (ADVICENOTE_ID) references
APP.ADVICENOTE
Hibernate: select categories0_.NAME as col_0_0_ from APP.CATEGORIES
categories0_
Hibernate: select items0_.ITEM_ID as ITEM_ID1_2_, items0_.NAME as
NAME2_2_, items0_.NET_PRICE as NET_PRIC3_2_, items0_.VAT_RATE as
VAT_RATE4_2_, items0_.CATEGORY_ID as CATEGORY5_2_ from APP.ITEMS
items0_
Hibernate: select items0_.ITEM_ID as ITEM_ID1_2_, items0_.NAME as
NAME2_2_, items0_.NET_PRICE as NET_PRIC3_2_, items0_.VAT_RATE as
VAT_RATE4_2_, items0_.CATEGORY_ID as CATEGORY5_2_ from APP.ITEMS
items0_
Hibernate: select categories0_.NAME as col_0_0_ from APP.CATEGORIES
categories0_
Hibernate: select items0_.ITEM_ID as ITEM_ID1_2_, items0_.NAME as
NAME2_2_, items0_.NET_PRICE as NET_PRIC3_2_, items0_.VAT_RATE as
VAT_RATE4_2_, items0_.CATEGORY_ID as CATEGORY5_2_ from APP.ITEMS
items0_
Is this normal behaviour or am I missing something?
Here are my XML mappings:
Advicenote.hbm.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">
<!-- Generated Feb 9, 2019, 3:57:52 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="classes.Advicenote" table="ADVICENOTE" schema="APP" optimistic-lock="version">
<id name="advicenoteId" type="int" column="ADVICENOTE_ID">
<generator class="native" />
</id>
<property name="advicedate" type="date" column="ADVICE_DATE" length="10" />
<property name="inOrOut" type="java.lang.Short" column="IN_OR_OUT" />
<many-to-one
name="partner" class="classes.Partner"/>
<set name="transactions" table="TRANSACTIONS" inverse="false" cascade="all" lazy="true" fetch="select">
<key column="ADVICENOTE_ID" not-null="true"/>
<one-to-many class="classes.Transactions"/>
</set>
</class>
</hibernate-mapping>
Categories.hbm.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="classes.Categories" table="CATEGORIES" schema="APP" optimistic-lock="version">
<id name="categoryId" type="int">
<column name="CATEGORY_ID" />
<generator class="native" />
</id>
<property name="name" type="string">
<column name="NAME" length="100" />
</property>
<set name="items" table="ITEMS" inverse="true" cascade="all" lazy="false" fetch="select">
<key>
<column name="CATEGORY_ID" not-null="true" />
</key>
<one-to-many class="classes.Items" />
</set>
</class>
</hibernate-mapping>
Items.hbm.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="classes.Items" table="ITEMS" schema="APP" optimistic-lock="version">
<id name="itemId" type="int" column="ITEM_ID">
<generator class="native" />
</id>
<property name="name" type="string" column="NAME" length="100"/>
<property name="netPrice" type="java.lang.Integer" column="NET_PRICE"/>
<property name="vatRate" type="java.lang.Integer" column="VAT_RATE"/>
<many-to-one name="category" class="classes.Categories" fetch="select" column="CATEGORY_ID" not-null="true" lazy="false"/>
</class>
</hibernate-mapping>
Limit.hbm.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="classes.Limit" table="LIMIT" schema="APP" optimistic-lock="version">
<id name="limitId" type="java.lang.Integer" column="LIMIT_ID">
<generator class="assigned"/>
</id>
<property name="value" type="int" column="LIMIT_VALUE" length="1000"/>
</class>
</hibernate-mapping>
Partner.hbm.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="classes.Partner" table="PARTNER" schema="APP">
<id name="partnerId" type="int">
<column name="PARTNER_ID"/>
<generator class="native"/>
</id>
<property name="partnerName" type="string" column="PARTNER_NAME" length="100"/>
<set name="advicenotes" table="ADVICENOTE" inverse="false" cascade="all" lazy="true" fetch="select">
<key column="PARTNER_ID" not-null="true"/>
<one-to-many class="classes.Advicenote" />
</set>
</class>
</hibernate-mapping>
Transactions.hbm.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="classes.Transactions" table="TRANSACTIONS" schema="APP" optimistic-lock="version">
<id name="transactionsId" type="int" column="TRANSACTIONS_ID">
<generator class="native" />
</id>
<property name="flow" type="int" column="FLOW" not-null="true" />
<property name="netPrice" type="java.lang.Integer" column="NET_PRICE" />
<many-to-one name="advicenote" class="classes.Advicenote"/>
<many-to-one name="item" class="classes.Items" fetch="select" cascade="save-update" column="ITEM_ID" unique="true" not-null="true"/>
</class>
</hibernate-mapping>
An AdviceNote mapping JoinColumn is missing
<many-to-one name="partner" class="classes.Partner">
<join-column name="PARTNER_ID"/>
</many-to-one>

Unable to create a table and insert data inside the table using Hibernate 3.x framework

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.

Invalid Mapping Exception in hibernate.hbm.xml

I am posting my hbm file with the cfg file along with my error log. I found my questions based on similar problems are tried out their solution too but still my error is not fading away.
log
Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource net/viralpatel/hibernate/Employee.hbm.xml
Exception in thread "main" java.lang.ExceptionInInitializerError
at net.viralpatel.hibernate.HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
at net.viralpatel.hibernate.HibernateUtil.<clinit>(HibernateUtil.java:8)
at net.viralpatel.hibernate.Main.main(Main.java:13)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource net/viralpatel/hibernate/Employee.hbm.xml
at org.hibernate.cfg.Configuration.addResource(Configuration.java:569)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1584)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1552)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1531)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1505)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1411)
at net.viralpatel.hibernate.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
... 2 more
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from input stream
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:508)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:566)
... 9 more
Caused by: org.dom4j.DocumentException: Error on line 9 of document : The element type "generator" must be terminated by the matching end-tag "</generator>". Nested exception: The element type "generator" must be terminated by the matching end-tag "</generator>".
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:499)
... 10 more
Employee.hbm.xml
<?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="Employee" table="EMPLOYEE" >
<id name="employeeId" column="EMPLOYEE_ID">
<generator class="native">
</id>
<one-to-one name="employeeDetail" class="net.viralpatel.hibernate.EmployeeDetail"
cascade="save-update"></one-to-one>
<property name="firstname" column="firstname" />
<property name="lastname" column="lastname" />
<property name="birthDate" type="date" column="birth_date" />
<property name="cellphone" column="cell_phone" />
</class>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">tcs#1234</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="net/viralpatel/hibernate/EmployeeDetail.hbm.xml"/>
<mapping resource="net/viralpatel/hibernate/Employee.hbm.xml"/>
</session-factory>
In your Employee.hbm.xml you're not closing the generator tag.
Replace
<generator class="native">
by this
<generator class="native"/>
By looking at stack trace, you have not end the generator tag properly.
Please change your employee.hbm.xml file to end the <generator> element properly.
For Ex: It should be <generator class="native"/>

Duplicate key or integrity constraint violation message from server in Hibernate

I'm new to Hibernate. I'm trying to insert records into my MySQL DB. The first record was inserted properly when I run the Java application, and when I change the details in the code and try to run it again. It throws me error of Duplicate key or integrity constraint. My XML is
<?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.college.Student" table="STUDENT">
<id column="ID" name="id" type="long" />
<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>
I guess I need to change in this configuration file or Hibernate.cfg.xml because its a primary key . Please suggest me.
Following is the error
WARN: SQL Error: 1062, SQLState: 23000
Feb 18, 2016 11:49:36 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Duplicate key or integrity constraint violation message from server: "Duplicate entry '0' for key 'PRIMARY'"
Feb 18, 2016 11:49:36 AM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Feb 18, 2016 11:49:36 AM org.hibernate.internal.SessionImpl$5 mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [could not execute statement]
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)
Seems like you haven't incremented your primary key column, you will have to do something like this
<id column="ID" name="id" type="long" >
<generator class="increment" />
</id>
You need to give generator for primary key of your table which will auto generated.
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
Read this
You need to have an auto increment for an id column.
For MySQL the best choice is to use identity generator, because of MySQL supports it natively.
<id column="ID" name="id" type="long">
<generator class="identity"/>
</id>
Hibernate will create a table with auto_increment column and MySQL will care about auto increment id
create table STUDENT (
ID bigint not null auto_increment,
...
)
Using other generators is not optimal, because of Hibernate will use additional queries and a table (hibernate_sequence) to increment id.

Categories