What cascadeType should I use for an immutable hibernate entity?

Viewed 62

What cascade type should I use for a hibernate entity attribute whose fields can't be modified, but that can be reassigned to a new instance?

Example

    @ManyToOne(cascade = { CascadeType.REFRESH })
    @JoinColumn(name = "ADDRESS_ID", nullable = true)
    private Address address;

We can assign a new address to the current object, but we can't modify the fields of an existing address since the Addresses should be immutable in the database. We should be able to create new addresses along with the entity but not to delete them. What CascadeType should we use?

1 Answers

The CascadeType refers to the operation that should cascade over to the object of an attribute. If you call EntityManager.persist, it will cascade to attributes with CascadeType.PERSIST, for EntityManager.merge it is CascadeType.MERGE, for EntityManager.remove it is CascadeType.REMOVE, for EntityManager.refresh it is CascadeType.REFRESH and finally for EntityManager.detach it is CascadeType.DETACH and finally.

A cascade type for saving i.e. PERSIST/MERGE controls if changes done to an Address entity, that is reachable through that attribute, should be flushed during the respective operation. Since you don't want this instance to be changeable at all, these cascade types make no sense at all and since it is immutable, also REFRESH makes no sense.

To guarantee that no changes happen, you will have to encapsulate the entity properly by e.g. using field access and not expose setters.

Related