Duplicate key or integrity constraint violation message from server in Hibernate - java

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.

Related

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>

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

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>

Hibernate mapping xml one-to-one (many-to-one)

I'm trying to map a relationship between two classes which have a one-to-one relationship. After looking up on the internet it seems like people prefer to map it using many-to-one.
For example have have a class Order and a class Bill. Bill holds a FK to the invoice.
Here is my mapping for Bill:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Mar 21, 2016 10:46:20 PM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="domain.Bill" table="BILL">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>
<many-to-one name="order" class="domain.Order" column="ORDER_ID" unique="true" not-null="true"/>
</class>
</hibernate-mapping>
As you can see above, in my mapping of Bill I can specify the column of Fk to the Order, but what should I put in my mapping for Order since it does not have a Fk to Bill?
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Mar 21, 2016 10:46:20 PM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="domain.Order" table="ORDER">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>
<many-to-one name="bill" class="domain.Bill" ???? fetch="select"/>
</class>
</hibernate-mapping>
You should try to map it as it is: one-to-one.
The only reason that I am aware of why people may recommend many-to-one is because of the lazy loading issues on the inverse side of the one-to-one associations. Then you probably want a fake one-to-many association on the inverse side (after all it's the only logical inverse side of many-to-one).
However, take a look at this answer for different alternatives.

remove duplicate rows from database with hibernate

I have an hbm file which is as below:
<?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 auto-import="true" default-lazy="false">
<class name="com.saman.entity.hibernate.EmployeeEntity"
table="Employee" optimistic-lock="version">
<id name="id">
<column name="Id" sql-type="bigint"/>
<generator class="native"/>
</id>
<timestamp name="version" source="db"/>
<property name="firstName">
<column name="FirstName" sql-type="nvarchar(300)"/>
</property>
<property name="lastName">
<column name="LastName" sql-type="nvarchar(300)"/>
</property>
<property name="employeeType">
<column name="EmployeeType" sql-type="nvarchar(300)"/>
</property>
<set name="shifts" table="Shifts" inverse="true" lazy="true" fetch="select">
<key>
<column name="Id" not-null="true"/>
</key>
<one-to-many class="com.saman.entity.hibernate.ShiftEntity"/>
</set>
</class>
</hibernate-mapping>
now I wanted if I add an employee and persist it, if then I add another employee with the previous information, my system raises an exception and tell me that I have another employee in the database with that informations.
does hibernate give me this option?
Well just add this to your mapping
<properties name="firstName_lastName_unique" unique="true">
<property name="firstName"/>
<property name="lastName"/>
</properties>
I think I understand what you want to achieve. But I don't know if you search your problem in stackoverflow first. This might be your answer How to do multiple column UniqueConstraint in hbm?
Have you set an auto increment on the ID column in your database?
You already have a generator for the id value. This should generate a unique id, but it only does so if these two conditions are true:
The column either is defined as autoincrement (p. ex. MySQL) or has a sequence (p. ex. Oracle)
When saving a new row, the member variable id is set to 0.
I can imagine, when you save a new value with previous information, the variable id still has a value != 0, and in this case the database uses the given value instead of generating a new unique one, which will fail due to the unique constraint.
This error also can appear if there is a second unique index on the table.

Hibernate generated POJOs

I am fairly a newbie with hibernate but I have been using Netbeans and hibernate reverse engineering tool to generate POJOs from an existing schema. All the POJOs for each table are created just fine except for join tables which i believe it is supposed to be this way as I can see the associations are being created in the mapping files. But the problem comes when I attempt to execute HBL query I get an exception that one of my join tables is not mapped. I know there is a mapping entry in config file, the only thing I could think of is that my data model is incorrect. I have a fairly large ER model but the problem tables are
I have User, Student, Major and StudentMajor tables. Below are my create statements
CREATE TABLE IF NOT EXISTS `Portfolio`.`User` (
`919Number` INT(11) NOT NULL ,
`loginId` VARCHAR(45) NOT NULL ,
`password` VARCHAR(8) NOT NULL ,
`userType` VARCHAR(10) NOT NULL ,
`lastName` VARCHAR(45) NULL DEFAULT NULL ,
`firstName` VARCHAR(45) NULL DEFAULT NULL ,
PRIMARY KEY (`919Number`) );
CREATE TABLE IF NOT EXISTS `Portfolio`.`Student` (
`919Number` INT(11) NOT NULL ,
`LEVL_CODE` VARCHAR(10) NOT NULL ,
PRIMARY KEY (`919Number`) ,
INDEX `919Number` (`919Number` ASC) ,
CONSTRAINT `919Number`
FOREIGN KEY (`919Number` )
REFERENCES `Portfolio`.`User` (`919Number` )
ON DELETE NO ACTION
ON UPDATE NO ACTION);
CREATE TABLE IF NOT EXISTS `Portfolio`.`Major` (
`majorCode` VARCHAR(10) NOT NULL ,
`majorDescription` VARCHAR(45) NULL DEFAULT NULL ,
PRIMARY KEY (`majorCode`) );
CREATE TABLE IF NOT EXISTS `Portfolio`.`StudentMajor` (
`919Number` INT(11) NOT NULL ,
`majorCode` VARCHAR(10) NOT NULL ,
PRIMARY KEY (`919Number`, `majorCode`) ,
INDEX `studentmajor_919Number` (`919Number` ASC) ,
INDEX `studentmajor_majorCode` (`majorCode` ASC) ,
CONSTRAINT `studentmajor_919Number`
FOREIGN KEY (`919Number` )
REFERENCES `Portfolio`.`Student` (`919Number` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `studentmajor_majorCode`
FOREIGN KEY (`majorCode` )
REFERENCES `Portfolio`.`Major` (`majorCode` )
ON DELETE NO ACTION
ON UPDATE NO ACTION);
Here is my hibernate config file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="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/portfolio</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">jta</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>
<mapping resource="com/portfolio/hibernate/mappings/User.hbm.xml"/>
<mapping resource="com/portfolio/hibernate/mappings/Student.hbm.xml"/>
<mapping resource="com/portfolio/hibernate/mappings/Major.hbm.xml"/>
</session-factory>
</hibernate-configuration>
and I am using Netbeans hibernate POJO genereation tool. But when I run the queries I get the below exception:
org.hibernate.MappingException: An
association from the table
studentmajor refers to an unmapped
class:
com.portfolio.hibernate.mappings.Student
at
org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1252)
at
org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1170)
at
org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:324)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1286)
at
org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
Is there a possibility that this error is caused by the way I have modeled my tables? Any help will be appreciated.
As suggested I am including contents of the hbm.xml files for Student and Major.
Student:::
<hibernate-mapping>
<class name="com.jopos.Student" table="student" catalog="portfolio">
<id name="nineOneNumber" type="int">
<column name="nineOneNumber" />
<generator class="assigned" />
</id>
<many-to-one name="user" class="com.jopos.User" update="false" insert="false" fetch="select">
<column name="nineOneNumber" not-null="true" unique="true" />
</many-to-one>
<property name="levlCode" type="string">
<column name="LEVL_CODE" length="10" not-null="true" />
</property>
<set name="faculties" inverse="false" table="advises">
<key>
<column name="studentnineOneNumber" not-null="true" />
</key>
<many-to-many entity-name="com.jopos.Faculty">
<column name="facultynineOneNumber" not-null="true" />
</many-to-many>
</set>
<set name="majors" inverse="false" table="studentmajor">
<key>
<column name="nineOneNumber" not-null="true" />
</key>
<many-to-many entity-name="com.jopos.Major">
<column name="majorCode" length="10" not-null="true" />
</many-to-many>
</set>
<set name="enrolls" inverse="true">
<key>
<column name="nineOneNumber" not-null="true" />
</key>
<one-to-many class="com.jopos.Enroll" />
</set>
</class>
</hibernate-mapping>
Major:::
<hibernate-mapping>
<class name="com.jopos.Major" table="major" catalog="portfolio">
<id name="majorCode" type="string">
<column name="majorCode" length="10" />
<generator class="assigned" />
</id>
<property name="majorDescription" type="string">
<column name="majorDescription" length="45" />
</property>
<set name="students" inverse="true" table="studentmajor">
<key>
<column name="majorCode" length="10" not-null="true" />
</key>
<many-to-many entity-name="com.jopos.Student">
<column name="nineOneNumber" not-null="true" />
</many-to-many>
</set>
</class>
</hibernate-mapping>
We had similar problem. It was solved when we changed our MySql tables from MyISAM to InnoDB.
I hope it helps
Maxim
The Student class your exception is been refering to is fetched from:
com.portfolio.hibernate.mappings.Student
Your Student.hbm.xml holds Student in the package:
com.jopos.Student
Do resolve the reference issue. Make sure com.jopos.Major is refering to com.jopos.Student in its import. And also make sure table studentmajor and its mapping exist.

Categories