Friday, 26 September 2014

Hibernate Mapping and Java Reflection API

Let's see one example to understand how hibernate using java reflection api.

We have one table EVENTS with three fields EVENT_ID, EVENT_DATE and TITLE.

For EVENTS table hibernate mapping file we define as follow.


<hibernate-mapping package="com.test.domain">
    <class name="Event" table="EVENTS">
        <id name="id" column="EVENT_ID">
            <generator class="native"/>
        </id>
        <property name="date" type="timestamp" column="EVENT_DATE"/>
        <property name="title"/>
    </class>
</hibernate-mapping>


Now first question is 'Why does the date property mapping include the column attribute, but the title does not ?'


Answer : Hibernate by default uses the property name as the column name. This works for title, however, date is a reserved keyword in most databases so you will need to map it to a different name.



Second question is  Why 'date' field having type attribute whereas 'title' field have not ?

Answer : Hibernate will try to determine the correct conversion and mapping type itself if the type attribute is not present in the mapping.  This automatic detection done using Java Reflection API. 

java.lang.reflect.Field class is there in Java api which having method called getType()


This is the case with the date property. Hibernate cannot know if the property, which is of java.util.Date, should map to a SQL date, timestamp, or time column. Full date and time information is preserved by mapping the property with a timestamp converter.


Keep In Mind : This Reflection process done when the mapping files are processed. This can take time and resources, so if startup performance is important you should consider explicitly defining the type to use.





Thursday, 24 October 2013

How to use DynamicUpdate and SelectBeforeUpdate in Hibernate

If you are using openSession() then you have to use both DynamicUpdate and SelectBeforeUpdate to make it effective.

As openSession every time opens new session, any object you want to update, that object doesn't lies in that session so you have to use SelectBeforeUpdate to retrieve that object in session. Then and then hibernate can determine how many fields are actually changed. So hibernate will update only changed field as we have set DynamicUpdate=true.

If you are using annotation then syntax should be like
@Entity
@Table(name = "Abc", catalog = "xyz")
@org.hibernate.annotations.Entity(dynamicUpdate = true, selectBeforeUpdate = true)
public class Abc implements java.io.Serializable {
       ...
       ...
}

If you are using latest jar files then dynamicUpdate  and selectBeforeUpdate are deprecated.
For that syntax should be like
@Entity
@Table(name = "Abc", catalog = "xyz")
@DynamicUpdate
@SelectBeforeUpdate
public class Abc implements java.io.Serializable {
       ...
       ...
}

And if you are using getCurrentSession() then no need to use SelectBeforeUpdate as object is already lies in session.

I recommend that use openSession() method instead getCurrentSession() because getCurrentSession automatically flush the session as well as close the session. It may chance to face problem in getCurrentSession method. While in openSession we have to manage all the things.





Wednesday, 24 July 2013

Disable browser back button when session has expired



Simply add following jquery code in your jsp file.

<script type="text/javascript">
$(function(){
     window.history.forward();
     function noBack() {window.history.forward(); }
     window.onpageshow=function(evt){if(evt.persisted)noBack();};
     window.onunload=function(){void(0);};
});
</script>


Alternative you can add following scriptlet in jsp file also.

<%
response.setHeader("Pragma", "no-cache");  
response.setHeader("Expires", "0");  
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
%>


Thursday, 21 March 2013

What is Open Source?


Owned by the Community, for the Community


Unlike commercially-licensed software, open source software is developed collaboratively and is owned by a community. The source code is freely available, and users are permitted and encouraged to change, improve, and – depending on the terms of the open source license – redistribute the software.
The result is a paradigm that moves development teams away from being locked into a vendor and provides benefits from cost savings, access to source code and continued innovation.

Benefits of Open Source Software

Cost savings—Users do not pay a license fee to adopt open source software, nor do they pay for updates. This eliminates the large upfront cost typically associated with infrastructure development, and significantly reduces the total cost of the project.

Vendor neutrality—Open source software is developed and owned by the community. Users of the project are not locked in to a vendor’s platform or a single provider for services, nor are users forced to buy proprietary modules or adopt prerequisite technology.

Vendor neutrality—Open source software is developed and owned by the community. Users of the project are not locked in to a vendor’s platform or a single provider for services, nor are users forced to buy proprietary modules or adopt prerequisite technology.

Flexibility—By definition, open source projects make the source code available and are modifiable. This allows enterprises to better understand the code, fix bugs, and edit the code to add unique features. Users are never at the mercy of a vendor.

Right sized—Closed source vendors typically sell large, comprehensive suites and force customers to buy and maintain more software than they need. Community-owned open source projects are packaged the way users want then, and users to deploy just what they need.

Innovation—With a large community that includes end users contributing to the project, open source software has proven itself to be a practical vehicle for the latest technological advancements. And with a large community freely downloading and using the projects, code quality remains high.



What Open Source Is Not

The open source approach is a new paradigm for developing software, not a new name for an old marketing program or delivery channel.

Open source software is not freeware.

Freeware is usually proprietary and distributed in binary-only form so that the provider can retain some control over the user. While open source software is also free, in contrast, it is owned by a community whose primary motivation is to free users from vendor control.

Open source software is not shareware.

Shareware is copyrighted software that is free for a trial period or with certain features disabled, but users are expected to pay for it in order to deploy. Open source software consists of complete packages intended to be deployed in full production scenarios.

Open source development is not free.

The code is available without licensing fees, but services used to support development are comparably priced to services for commercially available software. Development teams may need to draw on the expertise of of others to architect, develop and deploy.




Thursday, 21 February 2013

When to use of initialize() method of Hibernate class

Suppose we have one class


public class Productmapping implements java.io.Serializable {

private Integer id;
private Customermaster customermaster;
private String abcValue;
private String xyzValue;
private boolean isDeleted;

         ..
         ..
         .... getter/setter

 @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customerId", nullable = false)
public Customermaster getCustomermaster() {
return this.customermaster;
}

public void setCustomermaster(Customermaster customermaster) {
this.customermaster = customermaster;
}
     
}


Here we declare FetchType = Lazy, so by default customermaster object of Productmapping class remains uninitialized when we retrieve productmapping object.


Now we want to retrieve single object(row) of Productmapping class which is initialized with customermaster object of class Customermaster.

Simply write one method in DAO class like...


public Productmapping getProductMappingFromId(int id) {

Productmapping productmapping = null;

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx=null;
try
{
tx = session.beginTransaction();

productmapping = (Productmapping)session.createCriteria(Productmapping.class)
.add(Restrictions.eq("id", id))
.add(Restrictions.eq("isDeleted", false))
.uniqueResult();

Hibernate.initialize(productmapping.getCustomermaster());


tx.commit();

}catch (Exception e) {
e.printStackTrace();
}

return productmapping ;
}


and you will get productmapping object initialized with Connectionmapping object.

Note : Must have to write Hibernate.initialize() method before committing transaction.





Friday, 28 December 2012

Retrieve limited field in hibernate

Assume we have hibernate generated POJO like

public class Customermaster implements java.io.Serializable {

private Integer customerId;
private String companyName;
private String contactPersonName;
private String contactNumber;
private String customerWebsite;
private String customerAddress1;
private String customerAddress2;
private String customerEmail;
private String customerZipCode;
private String customerCity;
private String customerState;
private String customerCountry;

        . . .
        .....
        . . .
}

Now we want only customerId, companyName and contactNumber in pojo object instead of Object[] or Map.

For that create constructor of that limited fields in pojo class.
Here we create contructor like

public Customermaster(Integer customerId, String companyName, String       contactNumber ) 
{
this.customerId = customerId;
this.companyName = companyName;
                this.contactNumber  = contactNumber ;
}

And finally we write query in dao like

List<Customermaster> customerList  =  List<Customermaster>)session.createQuery("select new Customermaster(cm.customerId ,cm.companyName, cm.contactNumber ) from Customermaster cm where .... ").list();

and we have list of Customermaster with only three fields, remains are null.