Removing parent and all children - java

I have a problem removing the parent entity from the database. The code looks like this:
public class Parent implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
#Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name="parentId")
private Set<Child> children = new HashSet<Child>();
}
public class Child implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
private String name;
}
Query q = em.createQuery("delete from Parent");
q.executeUpdate();
But I get "ERROR: update or delete on table "parent" violates foreign key constraint "fk2f04da924aeb47d8" on table "child"". Is it not possible to cascade the delete of all children? How should you clear the tables otherwise?

The bulk delete operation is not cascaded. From the JPA 1.0 specification:
4.10 Bulk Update and Delete Operations
(...)
A delete operation only applies to
entities of the specified class and
its subclasses. It does not cascade to
related entities.
(...)
So if you want to use a bulk delete, you'll have to do handle relations "manually" (i.e. to delete related entities first).
The other option would be to loop on the parent entities and to call em.remove() (and cascading would work).
Choosing one option or the other will depend on the number of entities to delete and the expected performances.

Related

JPA: Mapping crossed OneToOne and ManyToOne relations

I have two entities, which we'll call A and B. B always has A as a parent with a ManyToOne relation.
However, I need A to have a OneToOne relation with the latest record inserted in table B.
This is because I need to save multiple versions of B but 99% of the time will only need to use the most recent one.
This looks something like this:
#Data
#Entity
public class A {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Setter(AccessLevel.NONE)
private Long id;
/* Properties
...
*/
#OneToOne(optional = false)
private B latest;
}
#Data
#Entity
public class B {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Setter(AccessLevel.NONE)
private Long id;
/* Properties
...
*/
#Column(nullable = false)
private Date lastModified;
#ManyToOne(optional = false)
private A parent;
}
Now, the issue at hand is that I cannot seem to persist these entities as one always appears to be transient:
A cannot be persisted because latest references B, yet B is not persisted.
B cannot be persisted because parent references A, yet A is not persisted.
Attempting to do so results in:
java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : B.parent -> A
I tried wrapping the code responsible for persisiting them in a #Transactional method but the same happens:
#Transactional
public void saveAB(A parent, B child) {
parent.setLatest(child);
child.setParent(parent);
Arepository.save(parent);
Brepository.save(child);
}
I also thought of disregarding the OneToOne relation from A to B, instead having latest as a transient #Formula field which would query B to take the most recent record. However, #Formula seems to be limited to primitives, not full entities.
What would be the proper way to do this with JPA? Am I approaching this the wrong way?
Since A and B depend on each other they should probably be considered a single aggregate with A being the aggregate root.
This means you'd have only an ARepository and also CascadeType.ALL on the relationships.
The solution was to apply #JoinFormula as explained here.
#Data
#Entity
public class A {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Setter(AccessLevel.NONE)
private Long id;
/* Properties
...
*/
#ManyToOne
#JoinFormula(value = "(SELECT b.id FROM b " +
"WHERE b.id = id ORDER BY b.lastModified DESC LIMIT 1)")
private B latest;
}
Then on B:
#ManyToOne(optional = false)
private A parent;

Hibernate OneToMany cascade

I've created two entities with a OneToMany relationship but when I remove the parent manually from the database the children remain. I've tried different solutions but nothing seems to work. What am I doing wrong?
#Entity
#Table(name = "PARENT")
public class Parent implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
#OneToMany(cascade = CascadeType.PERSIST, orphanRemoval = true)
#JoinColumn(name = "parent_id")
public List<Child> children = new ArrayList<Child>();
}
#Entity
#Table(name = "CHILD")
public class Child implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer id;
}
I've tried different solutions like the one attached below, but for some reason when i delete the parent manually through commands the children remain after the parent was removed.
What is the difference between cascade and orphan removal from DB?
I suggest you may recheck your database tables. There should be a 'PARENT_ID' column in the 'CHILD' table. Which will prevent deleting a parent without deleting respective children by giving a foreign key violation error related to your database.
Please check your table structure for tables PARENT and CHILD in the database. There should be a foreign key reference to parent_id in the CHILD table and on delete cascade property set.
As per your models, there is no relationship from child to parent and hence the delete of parent is not cascading the child.
You can either create bidirectional relationship by adding #ManyToOne relationship from child to parent
or use #OnDelete(action = OnDeleteAction.CASCADE) property after specifying unidirectional #ManyToOne relationship from child side.

JPA insert parent/child results in MySQLIntegrityConstraintViolationException

This has already been asked a number of times, but I don't find any good answers so I'll ask it again.
I have parent-children unidirectional relation as follows:
#Entity
#Table(name = "PARENT")
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private Long parentId;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
#JoinTable(name = "CHILD", joinColumns = #JoinColumn(name = "parent_id"), inverseJoinColumns = #JoinColumn(name = "ID"))
private List<Child> children;
}
#Entity
#Table(name = "CHILD")
public class Child {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private Long id;
#Column(name = "PARENT_ID")
private Long parentId;
//some other field
}
I create an instance of the parent, assign a list of children to it and try to persist it:
Parent p = new Parent();
List<Child> children = new ArrayList<Child>();
Child c = new Child();
children.add(c);
p.addChildren(children);
em.merge(p);
When the code runs, I get the following exception:
MySQLIntegrityConstraintViolationException: Cannot add or update a
child row: a foreign key constraint fails
(testdb.child, CONSTRAINT parent_fk
FOREIGN KEY (parent_id) REFERENCES parent (id) ON
DELETE NO ACTION ON UPDATE NO ACTION)
I'm assuming this is due to the fact that the parent is not fully inserted when the child is being attempted to be inserted.
If I don't add the children to the parent, the parent gets inserted just fine.
I tried switching the GeneratedValue generation strategy but that did not help.
Any ideas how to insert the parent & the children at the same time?
Edit: Even if I persist the parent first, I'm still getting the same error. I determined it's because the parent_id is not set in the child; the child is default constructed and thus the parent_id is set to 0 which does not exist thus the foreign key constraint validation.
Is there a way to get jpa to automatically set the parent_id of the children that are assigned to the parent instance?
Your relationship does not have to be bi-directional. There is some mis-information in the comments here.
You also said that you had added the field "parentId" into the Child entity because you assumed that JPA needs to "know" about the parent field so that it can set the value. The problem is not that JPA does not know about the field, based on the annotations that you have provided. The problem is that you have provided "too much" information about the field, but that information is not internally consistent.
Change your field and annotation in Parent to:
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
#JoinColumn(name = "parent_id")
private List<Child> children;
Then remove the "parentId" from the Child entity entirely.
You had previously specified a JoinTable annotation. However, what you want is not a JoinTable. A JoinTable would create an additional third table in order to relate the two entities to each other. What you want is only a JoinColumn. Once you add the JoinColumn annotation onto a field that is also annotated with OneToMany, your JPA implementation will know that you are adding a FK into the CHILD table. The problem is that JPA has a CHILD table already defined with a column parent_id.
Think of it that you are giving it two conflicting definitions of both the function of the CHILD table and the parent_id column. In one case, you have told you JPA that it is an entity and the parent_id is simply a value in that entity. In the other, you have told JPA that your CHILD table is not an entity, but is used to create a foreign key relationship between your CHILD and PARENT table. The problem is that your CHILD table already exists. Then when you are persisting your entity, you have told it that the parent_id is explicitly null (not set) but then you have also told it that your parent_id should be updated to set a foreign key reference to the parent table.
I modified your code with the changes I described above, and I also called "persist" instead of "merge".
This resulted in 3 SQL queries
insert into PARENT (ID) values (default)
insert into CHILD (ID) values (default)
update CHILD set parent_id=? where ID=?
This reflects what you want perfectly. The PARENT entry is created. The CHILD entry is created, and then the CHILD record is updated to correctly set the foreign key.
If you instead add the annotation
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
#JoinColumn(name = "parent_id", nullable = false)
private List<Child> children;
Then it will run the following query when it inserts the child
insert into CHILD (ID, parent_id) values (default, ?)
thus setting your FK propertly from the very beginning.
Adding updatable=false to the parent entity solved the problem with both an insert and an updated being executed on the child table. 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.
I know persisting a new parent with children works for me using em.persists(...).
Using em.merge(...), really I don't know, but it sounds like it should work, but obviously you are running into troubles as your JPA implementation is trying to persists children before parent.
Maybe check if this works for you : https://vnageswararao.wordpress.com/2011/10/06/persist-entities-with-parent-child-relationship-using-jpa/
I don't know if this plays a role in your problem, but keep in mind that em.merge(p); will return a managed entity... and p will remain un-managed, and your children are linked to p.
A) try em.persists(...) rather than em.merge(...)
if you can't
B) you are merging parent... and you cascade is set to CascadeType.PERSIST. Try changing it to
cascade=CascadeType.ALL
or
cascade={CascadeType.PERSIST, CascadeType.MERGE}
I know merge will persists newly created entities and should behave as persists, but these are my best hints.
What you wantto achieve you can achieve with this code.
#Entity
#Table(name = "PARENT")
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private Long parentId;
#OneToMany(cascade = CascadeType.PERSIST)
private List<Child> children;
}
#Entity
#Table(name = "CHILD")
public class Child {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private Long id;
#ManyToOne
Parent parent;
}

Remove parent entity without removing children (jpa)

I'm trying to remove list of parent without removing children
The parent :
#Entity
public class Parent {
#Id
#Column(name = "PARENTID")
private Long id;
#OneToMany(cascade = {CascadeType.ALL}, mappedBy = "parent")
private Set<Child> childs = new HashSet<Child>();
...
}
The child:
#Entity
public class Child {
#Id
#Column(name = "CHILDID")
private Long id;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="PARENTID", nullable = false)
private Parent parent;
...
}
What i did is to update all children using HQL query, and then delete the list of parents using HQL query as well.
The problem is that this way is too heavy, is there any simple solution using JPA ?
you could set your Cascade in the following section to not delete
#OneToMany(cascade = {CascadeType.ALL}, mappedBy = "parent")
private Set<Child> childs = new HashSet<Child>();
by editing the annotation as follows:
#OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST}, mappedBy = "parent")
and whatever other CascadeType options you need ( see CascadeType Enums). This will make it so that when you delete the parents, the children won't be deleted as well.
The mapping as it is does not allow for a simple deletion of parents with their children. It does not support having a Child without a Parent (nullable = false).
You either need to
set the parent id to a 'surrogate' Parent before removal of the parents. You can do it by a bulk update or by fetching the parents that are about to be deleted, iterate over the children and reset the parent references. Whether you use bulk updates or object manipulation depends on how you would remove the parents. If you remove the parents with a bulk query, use a bulk query for the children as well. In general I would use the object approach as the safer one. The bulk query is more compact.
drop the nullability constraint and change the provided cascade. Remove the REMOVE cascade from the #OneToMany mapping and you can remove parents as you like.

saving mapped collection in new entity

I've read the documentation and thought I'd be able to do the following....
map my classes as so (which does work)
#Entity
public class ParentEntity
{
...
#OneToMany(mappedBy = "parent")
private List<ChildEntity> children;
...
}
#Entity
public class ChildEntity
{
...
#Id
#Column
private Long id;
...
#ManyToOne
#NotFound(action = NotFoundAction.IGNORE)
#JoinColumn(name = "parent_id")
private ParentEntity parent;
...
}
.. but i want to be able to insert into both tables in one go and thought this would work:
parent = new ParentEntity();
parent.setChildren(new ArrayList<ChildEntity>());
ChildEntity child = new ChildEntity();
child.setParent(parent);
parent.getChildren().add(child);
session.persist(parent);
Can anyone tell me what i'm missing?
Do i need to save the parent first, then add the child and save it again?
thanks.
You have to add #OneToMany(cascade=CascadeType.PERSIST). You can also have CascadeType.ALL which includes persist, merge, delete...
Cascading is the setting that tells hibernate what to do with collection elements when the owning entity is persisted/merged/deleted.
By default it does nothing with them. If the respective cascade type is set, it invokes the same operation for the collection elements that were invoked for the parent.

Categories

Resources