Example of @Immutable in Hibernate Annotation

By Arvind Rai, January 31, 2013
In Hibernate Annotation if we want to make an entity immutable, @Immutable can help. @Immutable will not allow the entity to be modified. We can initialize an immutable entity one time but onwards it will not be modified. If we try to modify, hibernate will not throw error. It will silently be discarded. In the example we have an immutable entity. We will initialize our entity then we will update and it will not be updated. In this way entity becomes read-only.

There are more options to make entity read only. Find the link

Hibernate Make Entity Read Only Example with Session.setDefaultReadOnly(), Session.setReadOnly(), Query.setReadOnly(), Criteria.setReadOnly() and Immutable Entity

On this page we will discuss use of @Immutable annotation.

Create Entity using @Immutable Annotation

Find the entity using annotated with @Immutable at class level.
ContactNumber.java
package com.concretepage.persistence;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Immutable;
@Entity
@Table(name="contact_number")
@Immutable
public class ContactNumber implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	private int id;
	@Column(name="person_id")
	private int personId;
	@Column(name="mobile_number")
	String mobileNumber;
	public ContactNumber(int id,int personId,String mobileNumber){
		this.id=id;
		this.personId=personId;
		this.mobileNumber=mobileNumber;
	}
	public ContactNumber(){	}
    
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getPersonId() {
		return personId;
	}
	public void setPersonId(int personId) {
		this.personId = personId;
	}
	public String getMobileNumber() {
		return mobileNumber;
	}
	public void setMobileNumber(String mobileNumber) {
		this.mobileNumber = mobileNumber;
	}
} 

hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.url">
    jdbc:mysql://localhost:3306/hibernate</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    
    <mapping class="com.concretepage.persistence.ContactNumber"/>
   </session-factory>
</hibernate-configuration> 

Run Application

Find the class to run the application.
HibernateUtil.java
package com.concretepage.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.concretepage.persistence.ContactNumber;
public class HibernateUtil {
	private static final SessionFactory concreteSessionFactory;
	    static {
	        try {
	            concreteSessionFactory = new AnnotationConfiguration()
	                    .configure().buildSessionFactory();
	        } catch (Throwable ex) {
	            throw new ExceptionInInitializerError(ex);
	        }
	    }
	    public static Session getSession()
	            throws HibernateException {
	        return concreteSessionFactory.openSession();
	    }
	    public static void main(String... args){
	    	Session session=getSession();
	    	session.beginTransaction();
	    	ContactNumber c1=new ContactNumber(1,1,"7777777777");
	    	session.persist(c1);
	    	session.getTransaction().commit();
	    	session.refresh(c1);
	    	c1.setMobileNumber("8888888888");
	    	session.beginTransaction();
	       	session.update(c1);
	       	session.getTransaction().commit();
	       	session.refresh(c1);
	       	System.out.println(c1.getMobileNumber());
	    }
	} 

Output

Find the output.
Hibernate: insert into contact_number (mobile_number, person_id, id) values (?, ?, ?)
Hibernate: select contactnum0_.id as id0_0_, contactnum0_.mobile_number as mobile2_0_0_, contactnum0_.person_id as person3_0_0_ from contact_number contactnum0_ where contactnum0_.id=?
Hibernate: select contactnum0_.id as id0_0_, contactnum0_.mobile_number as mobile2_0_0_, contactnum0_.person_id as person3_0_0_ from contact_number contactnum0_ where contactnum0_.id=?
7777777777
In the example entity ContactNumber has the mobile number 7777777777 and now we have updated to 8888888888 and when we print the value result will be 7777777777. So hibernate did not allow to update the entity because it is immutable. You can test also removing @Immutable annotation, in this case update will be allowed.
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us