bidirectional OneToOne parent/child behavoiur

61 views Asked by At

I have a question concern hibernate: Imagine we have a situation

@Entity
@Table(name = "users")
public class User {

@OneToMany(mappedBy = "createdBy", fetch = FetchType.LAZY, targetEntity = Address.class)
private List<Address> investments = Collections.emptyList();

}

and

@Entity
@Table(name="addresses")
public class Address{

@ManyToOne(fetch = FetchType.LAZY, targetEntity = User.class)
@JoinColumn(name="USER_ID")
private User createdBy;

in this situation we have bidirectional relationship. In this scenario it is possible to remove only user without touching Addresses?

Because when I try to remove User using entityManager.remove(user) hibernate remove also Addresses connected with this user.

UPDATE: In above code by default we have orphanRemoval = false cascadeType = empty

from this parameters when I will try to delete user it should be deleted without address. But this doesn't happend. When I'll delete user it will delete together with address. Why is that?

1

There are 1 answers

2
Safwan Hijazi On

try to do the remove in this way:
// use your setter and getter names

    tx = em.getTransaction();   
    tx.begin();  
    User user = em.find(User.class,1);
    Address address = user.getAddress();
    address.setUser(null);
    user.setAddress(null);
    em.merge(address);
    em.remove(em.merge(user));
    tx.commit();