Unable to remove childs in OneToMany Mapping and add new childs [Hibernate]

47 Views Asked by At

I know this question has been asked many times but none of the solution is working for me.

So I have a Parent class :

class User{

@Id
@NotNull
@Column(name = "`UserId`", nullable = false)
private Long userId;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(name = "`UserId`")
private Set<Phone> phoneList;
}

And a child class:

class Phone {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "`UserId`")
private User user;
}

Now when I received a update for User class with new phone list, I want to remove all the old phones and add new phones. Please note that this all operation is happening in same @Transactional.

Solution I tried:

user.getPhoneList().clear()
user.getPhoneList().addAll(new phone list)

When I try the above logic, Hibernate is trying to set old phone with userId as null. At this position I am getting DataIntegrityViolation as userId in Phone table is non null column.

Please provide any appropriate solution which can work here.

1

There are 1 best solutions below

4
On

Hhhmmm... I have the exact same logic and it works fine by me. Here are my classes

@Data
@Entity
public class ProductReference {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;


@OneToMany(mappedBy = "productReference", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE, orphanRemoval = true)
private Set<Attribute> attributes = new HashSet<>();

}

The only difference I see is the CascadeType.REMOVE

@Data
@Entity
public class Attribute {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@ManyToOne
private ProductReference productReference;
}

My deletion:

productReference.getAttributes().clear();

Which Hibernate version you have? by me it is org.hibernate.Version - HHH000412: Hibernate Core {5.4.10.Final}