Wednesday, June 4, 2014

Dynamic insert and Dynamic update in Hibernate



Hibernate Dynamic insert and Dynamic update


1.       Dynamic insert: In hibernate by default dynamic insert attribute is false it means when an object is inserted to the database it will include all columns whose values are null i.e. it will generate an insert statement with all unnecessary columns. For example see below code.
        Stock stockTran = new Stock ();
        //stockTran.setPriceOpen(new Float("1.2"));
        //stockTran.setPriceClose(new Float("1.1"));
        //stockTran.setPriceChange(new Float("10.0"));
        stockTran.setVolume(2000000L);
        stockTran.setDate(new Date());
        stockTran.setStock(stock);

        session.save(stockTran);

make show_sql true in hibernate configuration and you will see following insert statement generated by Hibernate SQL.

INSERT 
    INTO
stock
        (DATE, PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN, STOCK_ID, VOLUME) 
    VALUES
        (?, ?, ?, ?, ?, ?)

Hibernate will generate the unnecessary columns (PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN) for the insertion.


Now make dynamic insert attribute true and try to insert the same stock object data and you will see that hibernate insert statement excludes all the null property values.
Now hibernate generates the following insert statement.
    INSERT 
    INTO
        stock
        (DATE, STOCK_ID, VOLUME) 
    VALUES
        (?, ?, ?)


Hibernate will generate only the necessary columns (DATE, STOCK_ID, VOLUME) for the insertion.

The main concern is performance issue
In some situations, such as a very large table with hundreds of columns (legacy design), or a table contains extremely large data volume, insert something not necessary definitely will drop down your system performance. So it is highly recommended to use the Dynamic Insert attribute true.

a.       Dynamic insert configuration using Annotation
@Entity
@Table(name = "stock ")
@org.hibernate.annotations.Entity(
              dynamicInsert = true
)
public class Stock implements java.io.Serializable {}
 
 
b.      Dynamic insert configuration using XML
<class ... table="stock " dynamic-insert="true">
        <id name="stockId" type="java.lang.Integer">
            <column name="STOCK_ID" />
        </id>

 



2.       Dynamic Update: By default hibernate set this attribute false means when we updated an object to the database using hibernate it generate the update SQL for all columns i.e. also for the columns those are not modified due to this update statement we face the system performance issue if we are playing with a table which has many columns or more data.
For example see the below code.

Query q = session.createQuery("from Stock where stockId = : stockId");
   q.setParameter("stockId ", 11);
   Stock stock = (Stock)q.list().get(0);
 
   stock.setVolume(4000000L);
   session.update(stock);
 
 
Hibernate will generate the following update statement
 
    UPDATE
        stock 
    SET
        DATE=?,
        PRICE_CHANGE=?,
        PRICE_CLOSE=?,
        PRICE_OPEN=?,
        STOCK_ID=?,
        VOLUME=? 
    WHERE
        STOCK_ID=?
 
That is hibernate will update all the unmodified columns.
 
But when we make dynamic update attribute true which means all the unmodified columns will be excluded from the updated statement.
For the above written update code hibernate will generate the following sql.
 
UPDATE
stock 
    SET
        VOLUME=? 
    WHERE
        STOCK_ID=?
 
That is hibernate will updated the modified columns only.
 
Performance Concern: 
In a large table with many columns (legacy design) or contains large data volumes, update some unmodified columns are absolutely unnecessary and great impact on the system performance. So we should use the dynamic update attribute true.

a.       Dynamic update configuration using Annotation
@Entity
@Table(name = "stock ")
@org.hibernate.annotations.Entity(
         dynamicUpdate = true
)
public class Stock implements java.io.Serializable {}
 
b.      Dynamic update configuration using XML
<class ... table="stock " dynamic-update="true">
        <id name="stockId" type="java.lang.Integer">
        <column name="STOCK_ID" />
 
//add generator
        </id>
 


Tuesday, June 3, 2014

Prefer lists to arrays or Generic List VS Array

Generic List Vs Array


Consider the below mentioned code fragments.
// Fails at runtime!
Object[] objectArray = new Long[1];
objectArray[0] = "I don't fit in"; // Throws ArrayStoreException

but this one is not:
// Won't compile!
List<Object> ol = new ArrayList<Long>(); // Incompatible types
ol.add("I don't fit in");

Either way you can’t put a String into a Long container, but with an array you
find out that you’ve made a mistake at runtime; with a list, you find out at compile
time. Of course you’d rather find out at compile time.

The second major difference between arrays and generics is that arrays are
reified [JLS, 4.7]. This means that arrays know and enforce their element types at
runtime. As noted above, if you try to store a String into an array of Long, you’ll
get an ArrayStoreException. Generics, by contrast, are implemented by erasure
[JLS, 4.6]. This means that they enforce their type constraints only at compile
time and discard (or erase) their element type information at runtime. Erasure is
what allows generic types to interoperate freely with legacy code that does not use
generics

Thursday, April 17, 2014

Why it happens?

String s1="hello"; String S2= s1+ " world"; String S3="helloworld"; is (s2==s3)?? if no why,  if yes why?

Saturday, February 15, 2014

Make an option in select box readonly not disabled using jquery.

HTML

//HTML Code
<select name="select1" id="select1">
    <option>No Match</option>
    <option value="1">Test</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>

<select name="select2" id="select2">
    <option>No Match</option>
    <option value="1">Test</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>

Jquery Code

//JavaScript Code

$('#select1').change(function() {
    
    var value = $(this).val();
  $('#select2').children('option').each(function() {
        if ( $(this).val() != value ) {
            $(this).attr('disabled', true);   
        }
    });
    
});

Friday, November 23, 2012

ResultTransformer in Hibernate

Retrieving a non managed entity from database using hibrnate.

If an entity is not mapped to the configuration file and we try to retrieve it from the database generatlly it throws mapping exception.

To get ride of such a situation we can user ResultTranform to retrieve the datafrom the database and map it to a bean which is not an entity or mapped in configuration.

Cautions:Attributes name and datatype in bean and the database should be same.

See the below the snap of code to implement ResultTransformer.

            Session session=Connector.getSession();
            Transaction tx=session.beginTransaction();
                  
           Query query=session.createSQLQuery("SELECT * FROM customer");
           
           List<Customer> list= query.setResultTransformer(Transformers.aliasToBean(Customer.class)).list()
;
    
     Note: Customer is a non mapped entity it is simple a java bean.

Saturday, October 20, 2012

Image Filter for reading image

/*This filter is used to add image location into front of image file.
we can get image from name without pass full path into jsp/html
Similar 
we can do for js and css file also
.
*/
import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;





public class ImageFilter implements Filter {



     */

    public ImageFilter() {

        // TODO Auto-generated constructor stub

    }



                /**

                * @see Filter#destroy()

                */

                public void destroy() {
S
                                // TODO Auto-generated method stub

                }



                /**

                * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)

                */

                public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

                                // TODO Auto-generated method stub

                                // place your code here

                                try

                                {



                                final HttpServletRequest req = (HttpServletRequest) request;

                                String imageName= RequestParser.getImageName(RequestParser.getCleanURI(req.getRequestURI()));

                                if(imageName!=null){
// used for location of image
                                                request.getRequestDispatcher("/WEB-INF/resources/images"+imageName).forward(request, response);

                                }

                                else{

                                                //return blank page here

                                                chain.doFilter(request, response);

                                }

                                }

                                catch(Exception exception)

                                {

                                                exception.printStackTrace();

                                }

                }



                /**

                * @see Filter#init(FilterConfig)

                */

                public void init(FilterConfig fConfig) throws ServletException {

                                // TODO Auto-generated method stub

                }



}

/****************************************************************/



import java.util.StringTokenizer;

/**

*


public  abstract class RequestParser {

              

               
                    /**

                     *

                     * @param URI

                     * @return clear uri from the requested uri, after removing project name

                     */

                    static final String getCleanURI(String URI) {



                        if (isURIOk(URI)) {

                            StringTokenizer tokens = new StringTokenizer(URI, "/");

                            StringBuilder cleanURI = new StringBuilder();

                            boolean first = true;

                            while (tokens.hasMoreElements()) {

                                //leave first token, or apply some other logic here so u can remove first part of uri

                                if (first) {

                                    tokens.nextElement();

                                    first = false;

                                    continue;

                                }

                                cleanURI.append("/");

                                cleanURI.append(tokens.nextElement());

                            }

                            return cleanURI.toString();

                        }

                        return null;

                    }



                    /**

                     *

                     * @param URI

                     * @return

                     * return image name parsing after image url

                     */

                    static final String getImageName(String URI) {

                        return (isURIOk(URI)) ? URI : null;

                    }



                

                    /**

                     *

                     * @param URI

                     * @return

                     * check if uri is ok or not

                     */

                    static final boolean isURIOk(String URI) {

                        return ((URI == null || URI.indexOf(".") == -1 || URI.indexOf("/") == -1)) ? false : true;

                    }



}
/***********************************************************/
 /*into web.xml*/
 <filter>
        <filter-name>ImageFilter</filter-name>
        <filter-class>ImageFilter</filter-class>/* add location of filter class*/
    </filter>
    <filter-mapping>
        <filter-name>ImageFilter</filter-name>
        <url-pattern>*.png</url-pattern>
    </filter-mapping>
   
    <filter-mapping>
        <filter-name>ImageFilter</filter-name>
        <url-pattern>*.jpg</url-pattern>
    </filter-mapping>
   
    /*  add other extension also*/
   

Thursday, October 4, 2012

Executing a task at a particular time interval using Schedular

public void startSchedular()
    {
        Scheduler scheduler = null;
        try
        {
String schedularTime=30 * * * 1-7//This will run after every 30 minutes for all 7 days
            scheduler = new Scheduler();
            scheduler.schedule(schedularTime, new Runnable()
            {
                @Override
                public void run()
                {
                    readEmails();
                }
            });
            scheduler.start();
        } catch (Exception e)
        {
            e.printStackTrace();// TODO: handle exception
            scheduler.stop();
        }
    }