Tech I Enjoy Logo

Custom Search




  Home >> Hibernate


Is there anyways to control insert, update of the fields of persist objects at runtime??

Yes, there are attributes arround property tag in the HBM configuration file
those can be used appropriately for controlling various functionalities
arround the way insert/update of fields/properties of persistent objects.

Suppose there is a field such as EmployeeId from a Employee class file, can it is
desirable to have this id immutable, or should not added or inserted from the 
business logic, instead this ID will be updated by some SQL script that is 
being executed by some other legacy application. In this situation we will have to
inform Hibernate not to consider those fields marked with certain attribute
such as insert="false". Like wise we can instruct Hibernate not to update
certain fields/properties by putting update="false" attribute in the 
respective HBM configuration XML file.

Similarly there are ways to instruct Hibernate about whether to include fields for those are modified or un-modified to be or not to be included as candidate for insert/update operations associated with the respective object. In HBM configuration file under class tag, we can have attributes like dynamic-insert="true" or dynamic-insert="false" and dynamic-update="true" or dynamic-update="false". I think these attributes are self-explainatory, for example dynamic-insert with value as true will make Hibernate to include all un-modified properties also in the insert SQL statement that is generated by Hibernate. Like-wise dynamic-update="false" means Hibernate will not include un-modified properties/fields during update SQL statement executed in database. In order to try out these setting I have created following example : SampleBean..java
package com.techienjoy.hibernate.example;

public class SampleBean {

    long id;
    String empId;
    String name;
    int age;
    String addrLine1;
    String addrLine2;
    String phone;
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getEmpId() {
        return empId;
    }
    public void setEmpId(String empId) {
        this.empId = empId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddrLine1() {
        return addrLine1;
    }
    public void setAddrLine1(String addrLine1) {
        this.addrLine1 = addrLine1;
    }
    public String getAddrLine2() {
        return addrLine2;
    }
    public void setAddrLine2(String addrLine2) {
        this.addrLine2 = addrLine2;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
}
with corresponding HBM XML file as follows: Example.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.techienjoy.hibernate.example">
   <class name="SampleBean" table="SAMPLE_BEAN">
    <id name="id" type="long" column="ID"/>
    <property name="empId" type="string" column="EMPID" insert="false"/>
    <property name="name" type="string" column="NAME"/>
    <property name="age" type="int" column="AGE"/>
    <property name="addrLine1" type="string" column="ADDRLINE1"/>
    <property name="addrLine2" type="string" column="ADDRLINE2"/> 
    <property name="phone" type="string" column="PHONE"/>               
   </class>

</hibernate-mapping>
And the Test harness code as follows: Test.java
package com.techienjoy.hibernate.example;

/**
 * This code is provided on "AS IS" basis, without warranty
 * or guaranty of any kind.
 * Author : TechiEnjoy
 * Date: 28-November-2010
 */
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Test {

    private static SessionFactory sessionFactory;

    /**
     * @param args
     */
    public static void main(String[] args) {

        try {
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
            SampleBean a = new SampleBean();
            a.setId(1001);
            a.setEmpId("E001");
            a.setName("Johney Rieder");
            a.setAddrLine1("Address Line 2");
            a.setAddrLine2("Address Line 2");
            a.setAge(45);
            a.setPhone("333-333-3333");
            
            Session session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();
            tx.begin();
            session.saveOrUpdate(a);
            session.flush();
            tx.commit();
            session.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

}
SQL found on Eclipse console :
Hibernate: select samplebean_.ID, samplebean_.empId as empId0_, samplebean_.NAME 
as NAME0_, samplebean_.AGE as AGE0_, samplebean_.ADDRLINE1 as ADDRLINE5_0_, 
samplebean_.ADDRLINE2 as ADDRLINE6_0_, samplebean_.PHONE as PHONE0_ from SAMPLE_BEAN 
samplebean_ where samplebean_.ID=?
Hibernate: insert into SAMPLE_BEAN (NAME, AGE, ADDRLINE1, ADDRLINE2, PHONE, ID) 
values (?, ?, ?, ?, ?, ?)
As you might noticed in the above Example.hbm.xml file, property empId is configured with a attribute as insert="false", this makes the final insert statement generated and executed by Hibernate, not included EMPID column in it. So even after setting a value for empId field in the test harness code, we can see null value for the corresponding column EMPID in database table. Like wise one can try puting dynamic-update="false" for a class tag and see the result to know and understand how this configuration setting works. SQL on console for the dynamic-update="false": Hibernate: update SAMPLE_BEAN set EMPID=?, NAME=?, AGE=?, ADDRLINE1=?, ADDRLINE2=?, PHONE=? where ID=? and SQL on console for the dynamic-update="true": Hibernate: update SAMPLE_BEAN set ADDRLINE1=? where ID=? Changed code for this to work as follows: Example.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.techienjoy.hibernate.example">
   <class name="SampleBean" table="SAMPLE_BEAN" dynamic-update="true">
    <id name="id" type="long" column="ID"/>
    <property name="empId" type="string" column="EMPID" insert="false"/>
    <property name="name" type="string" column="NAME"/>
    <property name="age" type="int" column="AGE"/>
    <property name="addrLine1" type="string" column="ADDRLINE1"/>
    <property name="addrLine2" type="string" column="ADDRLINE2"/> 
    <property name="phone" type="string" column="PHONE"/>               
   </class>

</hibernate-mapping>
And Test.java
package com.techienjoy.hibernate.example;

/**
 * This code is provided on "AS IS" basis, without warranty
 * or guaranty of any kind.
 * Author : TechiEnjoy
 * Date: 28-November-2010
 */
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Test {

    private static SessionFactory sessionFactory;

    /**
     * @param args
     */
    public static void main(String[] args) {

        try {
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
            SampleBean a = new SampleBean();
            a.setId(1001);
            a.setEmpId("E001");
            a.setName("Johney Rieder");
            a.setAddrLine1("Address Line 2");
            a.setAddrLine2("Address Line 2");
            a.setAge(45);
            a.setPhone("333-333-3333");
            
            Session session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();
            tx.begin();
            session.saveOrUpdate(a);
            a.setAddrLine1("ADD1");
            session.saveOrUpdate(a);
            session.flush();
            tx.commit();
            session.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
Hope this helps.
If anything missed out , please let me know at techienjoy at yahoo . com
Hibernate Bag Mapping Example :
class mapping using Bag Tag example using Hibernate
Framework and a simple to follow steps.
Hibernate Many to Many Mapping Example :
Many to many mapping example using Hibernate
Framework and a simple to follow steps.
Hibernate Property Formula :
Hibernate Example on Property
Tag with ease to do code walk-through
Hibernate Example on Filter :
Example on using Filter using Hibernate Framework
to work with.
Hibernate Example on composite Primary key :
Example on using Hibernate Framework
to work with mapping using composite
Primary key.
Hibernate one to many mapping Example :
one to many mapping explained using an example
and Hibernate Framework.
Example on persisting Class Hierarchy :
Example on using Hibernate Framework
to persist Class Hierarchy into database.
Hibernate one to many mapping Example :
one to many mapping explained using an example
and Hibernate Framework.
Hibernate Insert Update control :
Hibernate Example on controlling
insert and update attributes
Class Hierarchy Mapping Example :
class hierarchy mapping example using Hibernate
Framework and a simple to follow steps.
List of Examples on Hibernate :
List of example using Hibernate.
Hibernate one to one mapping Example :
one to one mapping explained using an example
and Hibernate Framework.
Hibernate class heirarchy mapping :
Hibernate Example on mapping
class hierarchy using various ways
of persisting into database
tables.
Hibernate Named Query Example :
Named Query markup using an example
and Hibernate Framework.
Hibernate Transaction on JBoss :
Explaining Transaction using Hibernate
on JBoss Application Server.
Hibernate Interview Questions :
Interview Questions on Hibernate with answer.
Hibernate Example on Filter Criteria :
Example on using Filter Criteria
using Hibernate Framework to work with.
Hibernate Join Example :
Using Table join explained with an example
while using Hibernate Framework.
Hibernate Interceptor Example :
Example on using Interceptor using Hibernate Framework
with source code explained.
Hibernate Component Property :
Hibernate Example on Component 
with source code explained.


References :
Tags: Hibernate Class Hierarchy Persist example
Tags: Hibernate composite primary key
Tags: Hibernate criteria filter example
Tags: Hibernate Filter Example
Tags: Hibernate Interceptor example
Tags: Hibernate Interview Questions
Tags: Hibernate join example
Tags: Hibernate Many to Many Mapping Example
Tags: Hibernate mapping bag
Tags: Hibernate mapping class hierarchy table per subclass
Tags: Hibernate named query markup
Tags: Hibernate One to Many mapping example
Tags: Hibernate One To One Mapping Example
Tags: Hibernate scenario one to many
Tags: Hibernate transaction jboss
Tags: Hibernate



DISCLAIMER :
The content provided in this page is not warranted and/or guaranteed by techienjoy.com. 
techienjoy.com is not liable for any negative consequences that may result/arise from 
implementing directly/indirectly any information covered in these pages/articles/tutorials.

All contents of this site is/are written and provided on an "AS IS" basis,
without WARRANTIES or conditions of any kind, either express or implied, including, without
limitation, merchantability, or fitness for a particular purpose. You are solely responsible
for determining the appropriateness of using or refering this and assume any risks associated
with this.

In spite of all precautions taken to avoid any typo in these pages, there might be some 
issues like grammatical mistakes and typos being observed in these pages, techienjoy.com
extends sincerest apologies to all our visitors for the same.



Android Examples || Android Examples

© Copyright 2010-2012, TECHIENJOY, All Rights Reserved.      Privacy Policy     Disclaimer & Terms & Conditions