JPA - @PreRemove method behaviour

前端 未结 1 821
慢半拍i
慢半拍i 2021-02-14 16:24

I have 2 entities with many-to-many relationship. The Movie Entity is the owner of this relation, so when I want to delete an Actor Entity I use a method annotated @PreRemove to

相关标签:
1条回答
  • 2021-02-14 16:48

    That's a fundamental feature of JPA/Hibernate. All the changes made to attached entities are automatically made persistent: Hibernate manages them, so it compares their current state with their initial state, and automatically makes all the changes persistent.

    This is extremely useful, because you don't have to track all the entities that have been modified in a complex business method modifying lots of entities. And it's also efficient because Hibernate won't execute unnecessary SQL: if an entity hasn't changed during the transaction, no SQL update query will be executed for this entity. And if you modify entities and then throw an exception rollbacking the transaction, Hibernate will skip the updates.

    So, typical JPA code would look like this:

    void transfer(Long fromAccountId, Long toAccountId, BigDecimal amount) {
        Account from = em.find(Account.class, fromAccountId); // from is managed by JPA
        Account to = em.find(Account.class, ftoAccountId); // to is managed by JPA
        from.remove(amount);
        to.add(amount);
    
        // now the transaction ends, Hibernate sees that the state of from and to 
        // has changed, and it saves the entities automatically before the commit
    }
    

    persist() is used to make a new entity persistent, i.e. to make it managed by Hibernate.

    merge() is used to take a detached entity (i.e. an entity which is not managed by Hibernate, but already has an ID and a state) and to copy its state to the attached entity having the same ID.

    0 讨论(0)
提交回复
热议问题