A question about JPA Cascade and removing entity

前端 未结 4 723
时光取名叫无心
时光取名叫无心 2021-01-31 12:16

I have two entities called User and UserProfile in my data model. Here is how they are mapped.

Code from User Entity:

@OneToOne(cascade=CascadeType.ALL)
@P         


        
4条回答
  •  被撕碎了的回忆
    2021-01-31 13:03

    As said

    When i try deleting the UserProfile entity, the corresponding User entity still stays

    Maybe when you try to remove a UserProfile you get an integrity constraint violation from the database - do you use MyISAM engine in MySQL ?

    But as you does not says nothing about it. Maybe your UserProfile entity does not have a reference to a User entity.

    As said in JPA specification

    remove operation is cascaded to entities referenced by X, if the relationship from X to these other entities is annotated with the cascade=REMOVE or cascade=ALL annotation element value

    Something like

    UserProfile up = entityManager.find(UserProfile.class, id);
    
    entityManager.close();
    
    // Notice User is null outside a persistence context 
    // So user will be not removed from the database because UserProfile does not have a reference to it
    up.setUser(null);
    
    entityManager.getTransaction().begin();
    
    entityManager.remove(up);
    
    entityManager.getTransaction().commit();
    

    Or you have something like

    entityManager.getTransaction().begin();
    
    UserProfile up = entityManager.find(UserProfile.class, id);
    
    // throws UPDATE USER_PROFILE SET USER_ID = NULL
    up.setUser(null);
    
    // up.getUser() is null
    // So user is not removed
    entityManager.remove(up);
    
    entityManager.getTransaction().commit();
    

    In response to ChhsPly's comment:

    In Java Persistence with Hibernate book, you see the following

    The cascade attribute is directional: It applies to only one end of the association.

    I think it would be better as

    It applies to only one end of the association per operation

    So you can put cascade attribute in both sides at the same time, even in a bidirectional relationship. So ChssPly is right.

    mappdeBy attribute sets up the bidirectional relationship. mappedBy attribute designated the Address entity as the inverse side of the relationship. This means that the Customer entity is the owning side of the relationship.

    ChssPly is right when he says mappedBy has nothing to do with cascading

提交回复
热议问题