Pages

Making Entity Immutable

Making Entity Immutable

You can use mutable attribute of class element in class mapping metadata. Default value of this attribute is true. If you make class as a immutable i.e mutable="false" than no UPDATE SQL statement will not be execute for this class or Entity.

If i run the following code than it will not execute any UPDATE SQL statement, 
Note: we have set mutable="false" for this case,


public class HibernateTest {
private final static Logger LOGGER = Logger.getLogger(HibernateTest.class); 
/**
* @param args
*/
public static void main(String[] args) {
LOGGER.info("starting of main method");
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction txn = session.beginTransaction();
Item item = (Item) session.get(Item.class, 1L);
item.setItemName("Nokia");
session.saveOrUpdate(item);
txn.commit();
session.close();
HibernateUtil.shutDown();
}
}
 
See the generated comments on console:

Oct 10, 2012 4:11:12 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: updating schema
Oct 10, 2012 4:11:12 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing extends queue
Oct 10, 2012 4:11:12 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing collection mappings
Oct 10, 2012 4:11:12 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing association property references
Oct 10, 2012 4:11:12 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing foreign key constraints
Oct 10, 2012 4:11:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: table found: HibernateTest.item
Oct 10, 2012 4:11:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: columns: [created_date, modified_date, item_name, item_id, item_amount]
Oct 10, 2012 4:11:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: foreign keys: []
Oct 10, 2012 4:11:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: indexes: [primary]
Oct 10, 2012 4:11:12 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: schema update complete
Oct 10, 2012 4:11:12 PM org.hibernate.impl.SessionFactoryImpl checkNamedQueries
INFO: Checking 0 named queries
Hibernate: /*load com.Item*/select item0_.ITEM_ID as ITEM1_0_, item0_.ITEM_NAME as ITEM2_0_0_, item0_.ITEM_AMOUNT as ITEM3_0_0_, item0_.CREATED_DATE as CREATED4_0_0_, item0_.MODIFIED_DATE as MODIFIED5_0_0_ from ITEM item0_ where item0_.ITEM_ID=?
Oct 10, 2012 4:11:12 PM org.hibernate.impl.SessionFactoryImpl close
INFO: closing



1 comment: