Hibernate one to many mapping DataIntegrityViolationException - java

Hibernate One to many relation Below Process will work
insert into parent table
insert into child table
update the parent primary key in child table
Suppose if i am having a foreign key constrain in database for parent and child table
my step 2 will fail as with DataIntegrityViolationException.
What is the best solution
Heading

You should go with hibernate inheritance feature to achieve this

Related

delete rows from multiple tables CONSTRAINT ERROR

I'm trying to erase information from two tables simultaneously that are connected with each other but not I am able to give me this error:
Can not delete or update a row parent: a foreign key constraint fails (socios.pagamentos,CONSTRAINT FK_FOREIGN KEY (nrSocio`) ON DELETE NO ACTION ON UPDATE NO ACTION)
screenshot
You could change your table design and make the relation delete cascade. In this case the child rows will be deleted automatically.
Or you could delete the records in a single statement like this
delete c, p
from parent_table p
left join child_table c on p.id = c.parent_id
where p.id = 1
If you delete from parent table,data in child tablr will not be able to refer parent table. This is why till thereare is a referrence ib child table, you can't delete from parent table. There are few ways to get rid of this situation.
Delete data from child table and then delete from parent table
You can use delete cascade relation in your table.
In this case, whenever you will delete data from parent table, data in child table will also be deleted.
The foreign key constraint can be removed to delete which is not a good approach.

Updating existing JPA child entities with FK in a single query

I have a parent/child one-to-many unidirectional relation.
Both the parent and the child POJOs use custom Insert-on-duplicate-update insert queries specified via #SQLInsert annotation.
Parent/child pair is inserted via cascading - everything works fine and the entity manager is closed.
Then I create a new entity manager and try to insert the same parent/child pair, but with updated values (same primary keys, but some of the other fields are changed).
The parent's Insert-on-duplicate-update works just fine and the values are updated.
In the child table however we end up with 2 entries, one with the old values and NULL parent_id foreign key, and one with the new values and correctly set FK.
I looked at the queries generated by Hibernate and found out the following:
The child row is inserted with the foreign key set to NULL
Then an update query is ran that sets the parent_id for the given child id
Another update is ran that sets the parent_id to NULL, I'm assuming for the child id of the first row
A third update query is ran that sets the parent_id
Is there a way for cascading insert to insert the child row and set the FK in the same query, thus eliminating the need for running a separate update query?
The question was answered as a part of a different question of mine:
JPA insert parent/child results in MySQLIntegrityConstraintViolationException
Basically, you have to set nullable = false in the #JoinColumn that specifies creates the parent/child relation.
There still seems to be an update query running for some reason but the complete record is being inserted with the insert statement.
The accepted answer did not solve my problem.
Adding updatable=false to the parent entity solved it. JPA does not execute the update query. However, I have no clue why that's the case and in fact, I don't think what I am doing is correct because it means I cannot update the child table later on if I have to.

Get the specific column involved in a FK Exception

I faced with the follow message error (DataIntegrityViolationException) in an attempt of delete a specific record in my table:
Cannot delete or update a parent row: a foreign key constraint fails (company.table_parent, CONSTRAINT table_parent_ibfk_1 FOREIGN KEY (id_son) REFERENCES layout (id))
I already know the cause: I'm attempting to delete a record, however, it is being used in other table.
I'd like to know if exist a attribute that contains the table and the column involved in transaction attempt, order to I could treat properly the exception without check the error message content.
I don't know if this call is included in an outer wrapped transaction. as I see it you can:
(A) make the call and parse the error message. You will know the table/col of violation.
(B) query for existence in FK table (either parent or child) for columns suspected of subsequent violation before the update/delete call.
another way of looking at B is that you might be doing this against the parent table and it is a child table that is barking saying you are about to orphan me

How change hibernate association mapping from 'one to many' into 'many to many'?

The relation between the entities must be changed and I'd like to know is it normal to change the association mapping type and whether the data that already exist in db will be transfered normally? I tried to find information about it but didn't found. Or if the mapping will be changed the data that already exists must be transfered manually via sql queries? Thanks
If the association already uses a join table, and the mapping of the many-to-many keeps using the same join table with the same column names, you won't have to do anything except removing the unicity constraint you could have on one of the ci=olumns of the join table.
Otherwise, yes, obviously, you'll have to migrate your schema, using SQL, or any other tool (FlywayDB, Liquibase, etc.).
I could do it simply:
Let A and B be the original tables.
A->B (N-1) was moved to A<-AB->B (N-N).
I had to
- "remove" the foreignkey column from table A,
in favor of records to be inserted into AB
(made of the two foreign keys leading to A and B)
That's all.
Step one: Replace your Many-to-One annotation by your Many-to-Many annotations.
and lauch hibernate in append mode to generate the N-N table
Step two: Insert record in this N-N table given what is found in the remaining foreign-key column of you 1-N relationship.
Step three: Delete this foreign-key column.

Is it proper to defined hibernate hbm file with id mapped to non-primary column in table

I have come across a hibernate hbm configuration where id attribute is mapped to a column in table which is not the primary key. The mapping is just used for read and not update. Though this works for most of the cases, I have found some cases where , when queried using get() on this mapping , it throws org.hibernate.HibernateException: More than one row with the given identifier was found
So my question is :
If I define a hbm with id mapped to non-primary key in table, can it allow more than two records with same id ?
At what layer is the primary key constraint checked, hibernate or database ?
Thanks,
Gaurav.
It will work if the column has all the features of a PK:
unique among all the rows of the table
immutable
The constraint is enforced at the database level. But Hibernate needs its ID to be unique. So it will choke if two rows have the same ID in database and are loaded in the same session.
I can't see any good reason to use a non-PK column as the ID of an entity, except if you're forced to map a legacy table, which can't change, and doesn't have any PK defined, even if one column or set of columns could be defined as the PK.

Categories