Hibernate Immutable

We can mark an Entity or a Collection as immutable. No annotation means the element is mutable.

An immutable entity may not be updated by the application. Updates to an immutable entity will be ignored, but no exception is thrown. @Immutable must be used on root entities only. Here the ‘update‘ operation will be ignore and no exception is thrown. @Immutable placed on a collection makes the collection immutable, meaning additions and deletions to and from the collection are not allowed. A HibernateException is thrown in this case.

The ‘mutable‘ can be used both in XML mapping file and Annotation.

1. Annotation

Entity

@Entity
@Table(name = "EMPLOYEE")
@Immutable
public class Employee  {
}


Collection

@OneToMany(mappedBy="employee")
@Immutable
private Set<Phone> phone;

2. XML Mapping

Entity

<class name="com.kruders.bean.Employee" table="EMPLOYEE" mutable="false" >
    <id name="employeeId" type="int" column="employee_id">
        <generator class="native" />
    </id>
...
</class>


Collection

<set name="phone" table="phone" inverse="true" lazy="true" fetch="select" mutable="false">
<key>
<column name="EMPLOYEE_ID" not-null="true" />
</key>
<one-to-many class="com.kruders.onetomany.Phone" />
</set>

No comments yet.

Leave a Reply