June 20, 2017

Arjun Rampal debuts as screenplay writer with Arun Gawli biopic, Daddy!

Arjun Rampal's much awaited film, Daddy is a biopic on gangster-politician Arun Gawli. Besides co-producing the project, Rampal has also forayed into script writing with this movie. He has been credited for co-writing the screenplay along with director Ashim Ahluwalia.

When Benny Dayal’s date got #LAPATA

While out partying with you, a gangster’s daughter goes missing. Yes, he is trying to hunt you down. No, there is no way out. You either suffer from the shock of a hundred different ways that you could be killed, or you try to prolong your lifeline, by running around endlessly in the city, trying to find her. Going to the cops isn’t an option either. So, how do you find her? More importantly, how do you save your life? Ask Benny Dayal and Dub Sharma, and you would know exactly what to do.

ALTBalaji welcomes Pammi Aunty and her family..

India’s largest OTT platform for original and exclusive digital shows, ALTBalaji brings a hilarious new show with Pammi Aunty to its viewers.  The digital show will showcase celebrated Pammi Aunty aka Ssumier Pasricha and her maddening dysfunctional family. The highlight of the yet to be named show is the fact that all the characters are played by Ssumier Pasricha himself.

June 17, 2017

Akash Gill to play pivotal role in 'Chakravyuh'..


Star Plus is coming up with a show 'Chakravyuh', which will be produced by Rolling Pictures and Taurus Media. After roping talented actors like Ajay Chaudhary, Sangeeta Ghosh, Narayani Shastri, Lubna Salim, Mahima Makwana, Sanyukta Timsina and Tom Alter, the makers of the show have now finalized Akash Gill to play a pivotal role in the show.

June 15, 2017

BARC Ratings (Impressions)- Week 23, 2017

We hope that Naagin’s ardent viewers enjoy watching Chandrakanta : Ekta Kapoor

As viewers prepare to bid adieu to the unprecedented leader on Indian television, Naagin 2, COLORS is all set to launch a fantastical tale of love and revenge portrayed against the backdrop of magic and mysticism, Chandrakanta. Promising to be a visual treat and every fantasy lover’s delight, Chandrakanta will showcase an epic power struggle between two rival Aiyaar kingdoms, Vijaygarh and Suryagarh. Putting the spotlight on the conflicting yet fervid relationship between princess Chandrakanta (Madhurima Tuli) and prince Veer (Vishal Aditya Singh), the show is laden with myths, legends and magic. Chandrakanta, produced by Ekta Kapoor’s Balaji Telefilms, will mystify audiences starting 24th June 2017, every Saturday and Sunday at 8:00 PM on COLORS.

Commenting on the launch of the show, Raj Nayak, COO - Viacom 18 said, “For two back-to-back seasons Naagin has enjoyed the status of being a favorite of the viewers. It’s their confidence in our content that has allowed us to explore this genre further. The recent success of costume dramas and fantasy offerings not only on television but also in films is a testimony that our viewers have evolved, and are willing to explore different narratives. We are thrilled to collaborate with Ekta Kapoor’s creative intellect yet again to showcase a unique rendition of a story which, though has been narrated before, leaves a lot of scope for creating a cohesive viewing experience.”

Chandrakanta narrates the tale of Vijaygarh’s lost princess who lost her family and kingdom to a power war waged by Naugarh’s evil Queen Iravati (Urvashi Dholakia). While many believed the family to be wiped out, an infant Chandrakanta was found in a river by a simple and loving aiyaar fishing couple in Suryagarh. Her true identity lost in the war, Chandrakanta grows up to be a strong warrior-like woman, whose focus and strong determination are unparalleled. But, her real journey starts when she crosses paths with Queen Iravati’s son, Prince Veerendra Singh, who finds himself enamored by Chandrakanta’s entrancing beauty and falls hopelessly in love with her when he comes to battle Suryagarh’s Prince Shivdutt (c).

Spread across a sprawling 32,000 square feet, Chandrakanta’s sets, designed by National Award winning Art Director Chandravadan More, highlight regality and opulence of the magical realms. Three distinct zones, Queen Iravati’s darbar in Vijaygarh, Prince Shivdutt’s darbar in Suryagarh, and Chandrakanta’s foster parents’ fisherman’s shack, have been authentically created to form the perfect setting for Chandrakanta and Veerendra’s love saga. Intricately designed costumes, by Sameera Ahmad, offer a kaleidoscope of vibrant colours which add a dimension to the complexity of the monolithic and prodigious backdrop.

Said Producer Ekta Kapoor from Balaji Telefilms at the launch, “Chandrakanta is a very special show for us and it has very big shoes to fill. That said, we were filled with excitement over the prospect of creating this show. The plot is gritty, complex, passionate and is laced with top class VFX which will transport the viewers into alternate reality. We hope that Naagin’s ardent viewers and voracious fantasy-fiction aficionados enjoy watching Chandrakanta and support this mammoth venture.”

Speaking on playing the title, actor Madhurima Tuli said, “Royalty by birth and a warrior by deeds, Chandrakanta has the innate ability to melt even the most ruthless warlords, outlaws and savage beasts. She is the perfect example of beauty with brains, and her fearless attitude and lack of vanity set her apart from every other woman. Chandrakanta’s focus is legendary, as much as her love for Veerendra. I am looking forward to this new journey and hope to live up to the audience’s expectations.”

Adding further, actor Vishal Aditya Singh aka Veerendra said, “Veerendra is fierce and ambitious, making him a strong warrior, who is ready to face anything that comes in his way. A charmer with a way with the ladies, Prince Veerendra will find himself allured by Chandrakanta’s beauty, intelligence and bravery. He’s obedient to a fault; he will be caught between his loyalty to his mother and his passionate love for Chandrakanta. It’s an honour for me to be a part of a path-breaking show and work with two entertainment masterminds, Balaji Telefilms and COLORS.”

Along with Madhurima Tuli, Vishal Aditya Singh, Urvashi Dholakia and Shaad Randhawa, Chandrakanta will feature an ensemble cast including actors Shilpa Sakhlani as Queen Ratnaprabha (Chandrakanta’s birth mother), Sandeep Ranjora as King Jai Singh (Chandrakanta’s birth father), Prerna Wanvari as Vishaka (Chandrakanta’s aunt), Nirmal Soni as Djinn (Chandrakanta’s best friend),  Shruti Golap as Ruchi (Chandrakanta’s adoptive aiyaar mother), Sayyad Mohammad Iqbal as Bheema (Chandrakanta’s adoptive aiyaar father), Purvi Mundada as Champa (Veerendra’s best friend), Amit Sinha as Kroor Singh (Shivdutt’s confidante) and many more.






June 13, 2017

Akshay Kumar will always be an idol for me : Kartik Aaryan

Pyaar Ka Punchnama fame Kartik Aaryan recently shot with ace photographer Dabboo Ratnani for a popular magazine. The pictures of the actor has set the mercury rising. The actor has worked on his body for his next film post Guest Iin London. The pictures from the shoot which have gone viral has Kartik flaunting his washboard abs, taut muscles and drool worthy body.

The credit for his transformation goes to famous celebrity fitness trainer Prashant Sawant who has been training stars like Shah Rukh Khan, Ajay Devgan, Varun Dhawan and many other top celebrities. It was a challenge for the actor to attain the perfect body, as Kartik is vegetarian and had limited choice for his diet. But nevertheless he achieved the most desirable physique.

IN PICS: Catch these new behind the scene stills from Tubelight


Munna Michael’s posters created a storm..

With every new Bollywood film, we get to know about the actor, director and musicians involved with the film but most people have no idea about the people who design the marvelous posters of a film.

June 12, 2017

'Kuch Rang Pyar Ke Aise Bhi' actress Khushbu feels shooting for two shows simultaneously can be quite taxing

Journalist-turned-actress Khushbu Thakkar, who is currently seen in 'Kuch Rang Pyar Ke Aise Bhi', will soon be seen in SAB TV's upcoming show 'TV Biwi Aur Mai'. The bubbly actress, who earlier did the shows like Geet Hui Sabse Parayi, Rangrasiya, Ishq Ka Rang Safed, will be seen as a creative director Tanvi in the show.

June 09, 2017

The magical hands behind Nawazuddin Siddiqui's transformation in Mom

When Nawazuddin Siddiqui's bald look for the movie Mom was revealed, the media and fans went ga-ga over it. So stunning and convincing was his artistic makeover, he was almost unrecognizable in pics of his special appearance character from the Sridevi Kapoor-Akshaye Khanna starrer. But not many are aware of the secret magical hands behind this overwhelming transformation.

June 07, 2017

Raabta’s court case verdict to be out tomorrow

Makers of Raabta argued for over 5 hours in court yesterday and today citing several differences in the script and storyline of their film Raabta and Magadheera. Their lawyers argued that the background of the lead characters, their storyline development, the role of villain,  the foreign locations and most importantly the finale of the film is completely and materially different from Magadheera.

Tubelight’s next song Tinka Tinka Dil Mera brings back Salman and Rahat!

Salman Khan is all set to team up with Rahat Fateh Ali Khan once again for the third song of his next much awaited film Tubelight. The song is called Tinka Tinka Dil Mera and is composed by Pritam. It is a beautiful melody about separation and heartbreak.

June 06, 2017

Glimpse of Sidharth Malhotra and Jacqueline Fernandez from - A Gentleman!

The makers of the much awaited Sidharth Malhotra and Jacqueline Fernandez starrer A Gentleman gave us a glimpse of what the film is all about. This only makes us eagerly await the trailer even more.

Kaala Teeka to go on air on Zee Anmol from 5th June..

Starting on 5th June 2017 at 10 PM, Zee Anmol will soon present its next primetime offering called Kaala Teeka.  It is the story of two young girls whose lives are entwined by an act of superstition. The show captures the journey of a girl child Kaali who is treated as a human Kaala Teeka for another child Gauri and is expected to shadow her everywhere for the well-being of the latter.

June 05, 2017

Implementing Inheritance in Hibernate

We will create a Mobile class, which is extended by two other classes. Both SamsungMobile and BlackberryMobile have one more variable samsungModelType and bbModel respectively.

1).
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "mobile_details")
public class Mobile {
    @Id @GeneratedValue
    private int mobileId;
    private String mobileName;
    //getters and setters
}

2).
import javax.persistence.Entity;
@Entity
public class SamsungMobile extends Mobile {
    private String samsungModelType;
    //getters and setters
}

3).
import javax.persistence.Entity;

@Entity
public class BlackberryMobile extends Mobile{
    public String bbModel;
    //getters and setters
}

4).
public class MobileTest {

    public static void main(String[] args) {
        Mobile mobile=new Mobile();
        mobile.setMobileName("Test Mobile Set");
       
        SamsungMobile samsung=new SamsungMobile();
        samsung.setMobileName("Samsung A series");
        samsung.setSamsungModelType("A5");
       
        BlackberryMobile blackberry=new BlackberryMobile();
        blackberry.setMobileName("Blackberry Curve Series");
        blackberry.setBbModel("C10");
       
        // create a session factory
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        // get the session from session factory
        Session savesession = sessionFactory.openSession();
        savesession.beginTransaction();
        // to save the object in hibernate       
        savesession.save(mobile);
        savesession.save(samsung);
        savesession.save(blackberry);
        savesession.getTransaction().commit();
        savesession.close();
    }
}


When you execute MobileTest, following queries are fired:
Hibernate: insert into mobile_details (mobileName, DTYPE, mobileId) values (?, 'Mobile', ?)
Hibernate: insert into mobile_details (mobileName, samsungModelType, DTYPE, mobileId) values (?, ?, 'SamsungMobile', ?)
Hibernate: insert into mobile_details (mobileName, bbModel, DTYPE, mobileId) values (?, ?, 'BlackberryMobile', ?)


Although we have marked SamsungMobile and BlackberryMobile as Entity class, but the hibernate has not created the seprate table, instead it has mapped the details in the base class table itself. This is because, by default hibernate use Single Table Strategy.



You can change the strategy, by added the @Inheritance annotation in the base class. e.g @Inheritance (strategy=InheritanceType.SINGLE_TABLE)

where, InheritanceType can be SINGLE_TABLE, TABLE_PER_CLASS or JOINED

mobile_details will have (DTYPE, mobileId, mobileName, samsungModelType, bbModel) columns with three rows having values (Mobile,1,Test Mobile Set,NULL,NULL), (SamsungMobile,2,Samsung A series,A5,NULL) and (BlackberryMobile,3,Blackberry Curve Series,NULL,C10)

where the column DTYPE contains the name of the entity class. Dtype is called Discriminator Type.

You can change the Discriminator Type, by adding @DiscriminatorColumn annotation in the base class. e.g:

@DiscriminatorColumn(name="mobile_type", discriminatorType=DiscriminatorType.STRING)

where, name will set the column name (which was previously the 'DType').
discriminatorType can be STRING, INTEGER or CHAR. By default STRING is the DiscriminatorType.

The discriminatorType by default stores the class name, but you can change it by adding @DiscriminatorValue annotation in the child class. e.g
@DiscriminatorValue ("Blackberry") and @DiscriminatorValue ("Samsung") can be added in BlackberryMobile and SamsungMobile respectively.

Now when you run MobileTest, it will fire below queries:
Hibernate: insert into mobile_details (mobileName, mobile_type, mobileId) values (?, 'Mobile', ?)
Hibernate: insert into mobile_details (mobileName, samsungModelType, mobile_type, mobileId) values (?, ?, 'Samsung', ?)
Hibernate: insert into mobile_details (mobileName, bbModel, mobile_type, mobileId) values (?, ?, 'Blackberry', ?)


mobile_details will have (mobile_type,mobileId,mobileName,samsungModelType,bbModel) columns with three rows:
(Mobile,1,Test Mobile Set,NULL,NULL)
(Samsung,2,Samsung A series,A5,NULL)
(Blackberry,3,Blackberry Curve Series,NULL,C10)


Example Of Inheritance With Table Per Class Strategy
@DiscriminatorColumn and @DiscriminatorValue are not needed in table per class strategy and you need to select strategy as InheritanceType.TABLE_PER_CLASS.

1).
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;

@Entity
@Table(name = "mobile_details")
@Inheritance (strategy=InheritanceType.TABLE_PER_CLASS)
public class Mobile {
    @Id @GeneratedValue
    private int mobileId;
    private String mobileName;
    //getters and setters
}
2).
import javax.persistence.Entity;
@Entity
public class SamsungMobile extends Mobile {
    private String samsungModelType;
    //getters and setters
}

3).
import javax.persistence.Entity;
@Entity
public class BlackberryMobile extends Mobile{
    public String bbModel;
    //getters and setters
}
When you execute MobileTest, following queries will be fired.
Hibernate: insert into mobile_details (mobileName, mobileId) values (?, ?)
Hibernate: insert into SamsungMobile (mobileName, samsungModelType, mobileId) values (?, ?, ?)
Hibernate: insert into BlackberryMobile (mobileName, bbModel, mobileId) values (?, ?, ?)
Separate tables for each class will be created. Parent class properties are inherited and they form the separate columns in the child tables.

Example Of Inheritance With Joined Strategy
We need to set strategy as InheritanceType.JOINED in the parent class.

When you run the MobileTest class after adding below line in parent Mobile class:
@Inheritance (strategy=InheritanceType.JOINED)
These queries will be executed:
Hibernate: insert into mobile_details (mobileName, mobileId) values (?, ?)
Hibernate: insert into mobile_details (mobileName, mobileId) values (?, ?)
Hibernate: insert into SamsungMobile (samsungModelType, mobileId) values (?, ?)
Hibernate: insert into mobile_details (mobileName, mobileId) values (?, ?)
Hibernate: insert into BlackberryMobile (bbModel, mobileId) values (?, ?)
  • mobile_details table will have two columns (mobileId, mobileName) and three rows: (1,Test Mobile Set), (2,Samsung A series) and (3,Blackberry Curve Series)
  • SamsungMobile table will have two columns (samsungModelType,mobileId) and one row:(A5,2)
  • BlackberryMobile table will have two columns (bbModel,mobileId) and one row:(C10,3)
-K Himaanshu Shuklaa..

Vivek Oberoi and Riteish Deshmukh at Radio Mirchi studio..

Ekta Kapoor puts the SHTICK in LIPSTICK..

Lipstick Under My Burkha, has been creating waves across social and mainstream media, not only because of its tryst with the censor board but also because of the fact that the film has travelled across the globe and gained immense appreciation and accolades.

May 22, 2017

Tusshar Kapoor, Sonakshi Sinha, Evelyn Sharma dress alike at Half Girlfriend screening!!

A recent special screening of the Arjun Kapoor-Shraddha Kapoor movie Half Girlfriend saw an unusual synchronization of minds that flummoxed many.

Amitabh Bachchan, Shabana Azmi, Sonu Nigam talk women empowerment

In the movie Bahubali 2, the character of Amarendra Bahubali played by Prabhas feels that merely chopping off the fingers of a man trying to grope women is not enough punishment. He beheads him as capital punishment. Now that can happen in the make-believe world of movies where things are often glorified and gory-fied. But in a dignified cultured society with better sensibilities, matters have to be drastically different.

May 19, 2017

Emma Watson’s dream comes true!

Emma Watson is much excited these days as her dream has come true! The actor has finally got a chance to work with her dream actor ‘Tom Hanks’ in their upcoming film “The Circle”.

The Harry Potter star confesses that it was an honour for her to share screen space with Hanks in their upcoming directoral by James Ponsoldt. Based on David Eggers’ book with same name, this techno-thriller hits Indian Cinemas under the banner of MVP Entertainment on May 19.

May 17, 2017

'God-woman' Radhe Maa turns actress!

Mamtamayi Radhe Maa aka Sukhvinder Kaur, who had grabbed national attention with an array of controversies is back with a bang. Well, this time in a brand new avatar.

May 15, 2017

RJ Malishka makes Bollywood debut with Vidya Balan's Tumhari Sulu..

The growing exciting cast of T-Series and Ellipsis Entertainment's Vidya Balan-starrer, Tumhari Sulu, has been in the news. From theatre ace Manav Kaul who will play Sulu's husband to the sexy Neha Dhupia who will essay the role of a radio boss, the quirky slice-of-life comedy, being directed by noted ad filmmaker Suresh Triveni, has become the talk of the town.

Is Shah Rukh Khan-luck rubbing off on Evelyn Sharma?


And you thought only Shah Rukh Khan and Salman Khan had fans waiting for them outside their Bandra residences. Wait till you are surprised!

A week ago, the Yeh Jawaani Hai Deewani (YJHD) actress Evelyn Sharma was taken aback to find two fans from Punjab waiting for autographs and selfies outside her Bandra abode. When she was preparing to leave for a shoot, they walked up to her and told her they had been coming there from two days and standing below her building for a couple of hours to get a peek of the actress.

May 14, 2017

Popular TV stars describe their mom in one sentence..

On the occasion of Mother’s Day, we spoke to a few popular TV celebs and asked them to describe their mom in one sentence. Here is what they said:
Urvashi Dholakia, who will be soon seen in yet another power packed role in Ekta Kapoor's Chandrakanta affirmed that she has a great respect for all the mother's not just today but everyday. "As a child, we wake up every morning and get to work and start our day. But Mothers wake up and pray. They pray for our joyous life, they pray so that we can remain strong. If they sense any trouble coming at us, they cut it like a knife. We as children need to understand that she will 'always' be holding our hand," says Urvashi.

IN PICS: Jamai Raja actor Sandit Tiwari ties the knot..

Sandit Tiwari, who did the shows like Beend Banoongaa Ghodi Chadhunga, Me Aajji Aur Sahib,  Jamai Raja and Mahisagar recently tied knot with his long time girlfriend Priyankona Das. She is a software professional and works with a leading IT firm.

May 10, 2017

Sridevi’s MOM to release in four languages!


 Boney Kapoor’s MOM presented by Zee Studios featuring superstar Sridevi, Nawazuddin Siddiqui and Akshaye Khanna will now be releasing nationwide in three languages including Tamil, Telugu and Malayalam besides Hindi.

Sridevi & A R Rahman promotes MOM on the sets of ‘Sa Re Ga Ma Pa Lil Champs 2017’!

Mother’s Day is just around the corner and to celebrate this special day, two special guests – superstar Sridevi and music maestro A R Rahman recently visited the sets of the singing reality show – Sa Re Ga Ma Pa Lil Champs to promote their forthcoming film, MOM.

Nadeem back with Suneel Darshan’s Ek Haseena Thi Ek Deewana Tha..

After launching the motion poster of Ek Haseena Thi Ek Deewana Tha, filmmaker Suneel Darshan has unveiled the musical teaser of his forthcoming musical thriller starring Upen Patel, Shiv Darshan and introducing sensational new find Natasha Fernandez.

May 09, 2017

Urvashi Dholakia learns horse-riding for Chandrakanta..

Urvashi Dholakia, who played the iconic role of Komolika Basu in 'Kasautii Zindagii Kay' will be playing an antagonist in Ekta Kapoor’s upcoming show Chandrakanta. She is playing a fearless, ambitious queen Iravati in the show, and is required to ride a horse. To get into the skin of the character, she went the extra mile and underwent extensive training in horse riding.

May 08, 2017

'Suit Suit' sensation Guru Randhawa sings for Vidya Balan's Tumhari Sulu..

The Punjabi "Suit Suit" sensation Guru Randhawa visited the set of T-Series & Ellipsis Entertainment's comedy "Tumhari Sulu" today. Guru's song Suit Suit was a chartbuster and he is now making aggressive inroads into Bollywood.

May 07, 2017

Hibernate Tutorial & Interview Questions And Answers

What is Hibernate?
Hibernate is an ORM tool and is used in the data layer of an application. It implements JPA (Java Persistence API), which is a set of standards that have been prescribed for any persistence implementation.

What is ORM?
ORM (Object Relational Mapping) is the fundamental concept of Hibernate framework which maps database tables with Java Objects and then provides various API’s to perform different types of operations on the data tables.



Suppose you want to store user information in the database. Most of the time, you will be using a relational database. You will be creating a user table, which has the columns corresponding to variables present in your Java class. i.e a class corresponds to a table, and an object of a class corresponds to a row in the table.  We need to write SQL queries, to select, insert, update details in the user table.

We have objects in Java, but not in the database, so we need to take the values of member variables from Java object and map it in the SQL queries. If you add a new column in the table, then you need to make changes in Java classes.

What if an object has a reference to another object, then you need to create tables with foreign keys.

Also, you need to manually do the data-type conversion.

Hibernate solves the above pain points.

Suppose, you want to save the object in the database, without Hibernate, we need to do following things:
  • We need to create the database table.
  • We need to do JDBC configuration.
  • We need to write a model object, which is the object which we need to save.
  • A service method, which will create this model object.
  • A DAO class, which will generate the SQL queries to save the object.
If you are using Hibernate, then you need to:
  • You need to write a hibernate configuration file (hibernate.cfg.xml), which will give information to Hibernate to which database it needs to connect.
  • Create a model object.
  • Write a service method, which will create an instance of a model object and pass it to Hibernate API.
Hibernate Annotations
  • @Entity annotation is used to mark the class as an Entity bean. So the class should have at least have a package scope no-argument constructor. When a Hibernate finds a class with @Entity annotations (entry of that class should be present in hibernate.cfg.xml), it will recreate it as a table in your database. If you specify name attribute with @Entity annotation e.g @Entity (name="User_Details"), then Hibernate will insert/ update/ fetch the record from User_Details, instead of from the table, whose name is same as Entity class name.
  • @Id annotation is used to specify the identifier property of the entity bean and should be kept above the member variable which you want to be used as primary key. The placement of the @Id annotation determines the default access strategy that Hibernate will use for the mapping. If the @Id annotation is placed over the field, then filed access will be used. Instead, if it placed over the getter method of that field, then property access will be used. Here we use property access.
  • @GeneratedValue annotation will tell hibernate to automatically generate values using an internal sequence. Therefore we don’t have to set it manually. We can use it along with @Id and make our primary key automatically generated rather than setting each time. We can also specify a strategy on how the values will be generated like @GeneratedValue(strategy=GenerationType.AUTO). AUTO is the default if we don’t give a strategy. Other values are IDENTITY, SEQUENCE and TABLE, which are actually dependent on the database that we use. AUTO is the preferred option as hibernate will chose the best strategy for us automatically.
  • @Column annotation is used to specify the details of the column to which a field or property will be mapped. If the @Column annotation is not specified by default the property name will be used as the column name. 
  • @Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If @Table annotation is not specified then Hibernate will by default use the class name as the table name. 
  • @Basic annotation without any parameters is same as without having it. It just tells hibernate to treat it is a field that needs to be saved and is the same behavior without it. However, the use comes when it is used along with its parameters. By default, it is same as @Basic (optional=true) and the field can be not supplied any value (not calling getter) or supplied with a null value. @Basic (optional=false) makes it a non-null field.  If not supplied any value (not calling getter) or supplied with a null value with @Basic (optional=false), you will get an exception: org.hibernate.PropertyValueException: not-null property references a null or transient value.
  • @Transient annotation tells Hibernate not to save this field. Even without this annotation, a static variable or a transient variable is not saved. So the behavior is same for a static variable, transient variable or any other variable with @Transient annotation. If annotations are placed over getters, those placed over fields are ignored and only getters are considered. Even other fields are ignored and all other getters are considered. Hence if you have annotations over any of your getter, then a static variable, transient variable or any other variable will be saved as usual if it has a getter.
  • @Temporal annotation over a date field tells hibernate the format in which the date needs to be saved. For instance, by default, the date will be saved as a timestamp, but to save date alone we can use @Temporal(TemporalType.DATE).
  • @Lob annotation tells Hibernate that this is a large object, not a simple object. So Hibernate creates a CLOB or BLOB based on the type of the object. For instance, if @Lob comes over a string, then Hibernate assumes to use a character large object (CLOB). In the case of array, it will treat it as BLOB.
  • @Embeddable and @Embedded annotations are used when you want to embed one entity in another entity. The attributes of an entity can be common attributes of more than one entity. An embeddable entity can be embedded in more than one entity. 

First Hibernate Application To Save And Fetch Objects using Hibernate APIs
We will be using SQL server 2012 for writing our Hibernate application.

Hibernate uses XML mapping file for the transformation of data from POJO to database tables and vice versa. We will first we need to write a configuration file.  Here is the example of hibernate.cfg.xml for SQL server
< ?xml version='1.0' encoding='UTF-8'? >
< !DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
< hibernate-configuration >
    < session-factory >
     < !-- Database connection settings -- >
        < property name="hibernate.connection.driver_class" >com.microsoft.sqlserver.jdbc.SQLServerDriver< /property >
        < property name="hibernate.connection.url" >jdbc:sqlserver://197.108.81.180:1233;databaseName=scrutinydb< /property >
        < property name="hibernate.connection.username" >khs< /property >
        < property name="hibernate.connection.password" >khs< /property >
       
        < !-- JDBC connection pool (use the built-in) -- >
        < property name="connection.pool_size" >1< /property >

        < !-- SQL dialect -- >
        < property name="dialect" >org.hibernate.dialect.SQLServer2012Dialect< /property >

        < !-- Disable the second-level cache  -- >
        < property name="cache.provider_class" >org.hibernate.cache.internal.NoCacheProvider< /property >

        < !-- Echo all executed SQL to stdout -- >
        < property name="show_sql" >true< /property >

        < !-- Drop and re-create the database schema on startup -- >
        < property name="hbm2ddl.auto" >create< /property >

        < !-- Names the annotated entity class -- >
        < mapping class="com.test.khs.UserDetails"/ >
    < /session-factory >
< /hibernate-configuration >


We need to write the Model Class with annotations and mention it in 'mapping' tag of hibernate.cfg.xml
package com.test.khs;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class UserDetails {
    @Id
    private int userId;
    private String userName;

    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}


Hibernate will create UserDetails, with two columns userId, userName and when you call save() method, the object will be saved in UserDetails table.
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.test.khs.UserDetails;
public class TestHibernate {
    public static void main(String[] args) {
        UserDetails user1=new UserDetails();
        user1.setUserId(1);
        user1.setUserName("Himaanshu Shuklaa");
       
        //create a session factory
        SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
        //get the session from session factory       
        Session savesession=sessionFactory.openSession();
       
        savesession.beginTransaction();
        //to save the object in hibernate
        savesession.save(user1);
        savesession.getTransaction().commit();
        savesession.close();
       
        //fetching
        user1=null;
        Session fetchsession=sessionFactory.openSession();
        fetchsession.beginTransaction();
        //fetch based on the primary key
        user1=fetchsession.get(UserDetails.class, 1);
        System.out.println("*****fetched UserDetails:"+user1.getUserName()+", Id="+user1.getUserId());
        fetchsession.close();
    }
}


If you execute TestHibernate again, then it will delete the previous record the UserDetails table and insert the new one again. This happens because of 'hbm2ddl.auto' property in hibernate.cfg.xml, which was,
< property name="hbm2ddl.auto" > create < /property >

To retain the previous data, you need to change 'create' to 'update'.

If you set hbm2ddl.auto to update and then execute TestHibernate class again, then it will insert a new record in the table.

Suppose you have executed TestHibernate with hbm2ddl.auto as 'create' or with 'update' and then added a new variable in UserDetails class. An error 'Invalid column name' when you try to execute TestHibernate with hbm2ddl.auto as 'update'.

Hibernate creates and insert the record in the UserDetails table, where the name of the table is same as Entity class name. What if the class name is different? Or you want to insert the record in a table with the different name? To resolve this issue by specifying the name in @Entity annotation. Also, by default the property name will be used as the column name, you can change it with the name property of @Column annotation.

Example of Hibernate Annotations @Embeddable and @Embedded

This example will add Address details in the Employee table.
1).
import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class Address {
    @Column(name = "street")
    private String street;
    @Column(name = "city")
    private String city;
   
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
        this.street = street;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }   
}

2).
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "employee_details")
public class Employee {
    @Id
    @Column(name = "id")
    private int empId;
    @Column(name = "emp_name")
    private String empName;
    @Column(name = "emp_address")
    @AttributeOverrides({
            @AttributeOverride(name = "street", column = @Column(name = "emp_add_street")),
             @AttributeOverride(name = "city", column = @Column(name = "emp_add_city"))})
    private Address empAddress;
    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public Address getEmpAddress() {
        return empAddress;
    }
    public void setEmpAddress(Address empAddress) {
        this.empAddress = empAddress;
    }   
}

3).
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class EmbedEmployeeTest {
    public static void main(String[] args) {
        Employee employee=new Employee();
        Address empAddress=new Address();
        empAddress.setCity("Kempten");
        empAddress.setStreet("Alfred-weitnauer-straße");       
        employee.setEmpId(1);
        employee.setEmpName("K Himaanshu Shuklaa");
        employee.setEmpAddress(empAddress);       
       
        //create a session factory
        SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
        //get the session from session factory       
        Session savesession=sessionFactory.openSession();
       
        savesession.beginTransaction();
        //to save the object in hibernate
        savesession.save(employee);
        savesession.getTransaction().commit();
        savesession.close();
    }
}


When you execute EmbedEmployeeTest, it will create employee_details table with id, emp_add_city, emp_add_street, emp_name as the columns with values 1, Kempten, Alfred-weitnauer-straße, K Himaanshu Shuklaa respectively.

What is the purpose of @ElementCollection annotation in Hibernate?
@ElementCollection annotation is used to persist the collections object in Hibernate.

JPA 1.0 only supported collection holding entity types using (@ManyToOne, @OneToMany) annotations. @ElementCollection is introduced in JPA 2.0, and it can be used with any collection of type Collection, List, Set, Map.

If you do not mention @JoinTable annotation, along with @ElementCollection, then it will create a table with user name 'ENTITYCLASSNAME_COLLECTIONMEMBERVARIABLENAME' e.g Department_listOfEmployees

FetchType: @ElementCollection supports Eager and Lazy types. What does these FetchType means? Suppose, you have an Department class, each department has list of Employees who are working in that department. You have fetched Department from 'session.get()', then only the member variables of Department class is fetched and Employees list is not retrieved from the database. The Employees list is retrieved when you call the getter for that embedded collection. This is called lazy initialization fetch in hibernate.

The alternative is called eager initialization fetch, in which the embedded collections are retrieved upfront.

To select the initialization type, you need to mention FetchType.EAGER or FetchType.LAZY along with @ElementCollection annotation. e.g '@ElementCollection (fetch=FetchType.EAGER)'. If you don’t specify the fetch parameter, the default is FetchType.LAZY.

In case of Lazy loading, after retrieving embedding class instance, if we will close session and then try to print the values of the embedded collection, we will get an exception as:org.hibernate.LazyInitializationException: failed to lazily initialize a collection…

This is because when you call session.get for embedding class, only embedding class fields (except the embedded collection) is retrieved. When we try to print the embedded collection details after session.close, there is no session available to retrieve the address details lazily and hence it throws an exception.
e.g:
Session fetchsession = sessionFactory.openSession();
fetchsession.beginTransaction();
Department department = fetchsession.get(Department.class, 1);
fetchsession.close();
department.getListOfEmployees();


Example Of Saving Collections In Hibernate
In the example, we will store Department details and multiple Employees work in the Department. So we will have an Employee class, and a Department has a Set of Employees. To do this, we need to use @Elementcollection annotation.

1).
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Table;

import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;

@Entity
@Table(name = "dept_details")
public class Department {
    @Id
    @Column(name = "dept_id")
    private int deptId;
    @Column(name = "dept_name")
    private String deptName;
   
    /*
    @ElementCollection
    @JoinTable (name="deptwise_employeedtls",
    joinColumns=@JoinColumn(name="deptid_fk"))
   
    private Set < Employee > listOfEmployees=new HashSet < Employee > ();
    public Set < Employee > getListOfEmployees() {
        return listOfEmployees;
    }
    public void setListOfEmployees(Set < Employee > listOfEmployees) {
        this.listOfEmployees = listOfEmployees;
    }
    */
   
    @ElementCollection
    @JoinTable (name="deptwise_employeedtls",
    joinColumns=@JoinColumn(name="deptid_fk"))
    @GenericGenerator(name="hilo-gen", strategy="hilo")
    @CollectionId(columns={@Column(name="employe-id")},generator="hilo-gen",type=@Type(type="long"))
    //if you want to define an primary key/id in Employee table, use list instead of set
    private Collection < Employee >  listOfEmployees=new ArrayList < Employee > ();   
    public Collection < Employee >  getListOfEmployees() {
        return listOfEmployees;
    }
    public void setListOfEmployees(Collection < Employee > listOfEmployees) {
        this.listOfEmployees = listOfEmployees;
    }
    public int getDeptId() {
        return deptId;
    }
    public void setDeptId(int deptId) {
        this.deptId = deptId;
    }
    public String getDeptName() {
        return deptName;
    }
    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }       
}

2).
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

//@Entity
@Table(name = "employee_details")
@Embeddable
public class Employee {
    //@Id
    @Column(name = "emp_id")
    private int empId;
    @Column(name = "emp_name")
    private String empName;

    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }   
}

3).
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.test.khs.UserDetails;

public class SaveDepartmentTest {
    public static void main(String[] args) {
        Department department=new Department();
        department.setDeptName("Import And Export");
       
        Employee employee1=new Employee();               
        employee1.setEmpId(1);
        employee1.setEmpName("K Himaanshu Shuklaa");
        Employee employee2=new Employee();               
        employee2.setEmpId(2);
        employee2.setEmpName("Tiger Shroff");
       
        /*
        Set < Employee > listOfEmployees=new HashSet < Employee > ();
        listOfEmployees.add(employee1);
        listOfEmployees.add(employee2);
        department.setListOfEmployees(listOfEmployees);
        */
       
        //create a session factory
        SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
        //get the session from session factory       
        Session savesession=sessionFactory.openSession();
       
        savesession.beginTransaction();
        //to save the object in hibernate
        savesession.save(department);
        savesession.getTransaction().commit();
        savesession.close();
       
        // fetching
        department = null;
        Session fetchsession = sessionFactory.openSession();
        fetchsession.beginTransaction();
        // fetch based on the primary key
        department = fetchsession.get(Department.class, 1);
        System.out.println("List Of Employees: for department name "+department.getDeptName()+" is "+ department.getListOfEmployees());
        fetchsession.close();
    }
}

Association Mappings
In our applications, most of the times our database tables are associated with each other. They can be associated by one-to-one, one-to-many, many-to-one and many-to-many relationship. These can be further divided into unidirectional and bidirectional mappings. Today we will look into implementing Hibernate One to One Mapping using XML configuration as well as using annotation configuration.

Component Mappings
It is very much possible that an Entity class can have a reference to another class as a member variable. If the referred class does not have it's own life cycle and completely depends on the life cycle of the owning entity class, then the referred class hence therefore is called as the Component class.

The mapping of Collection of Components is also possible in a similar way just as the mapping of regular Collections with minor configuration differences.

Example of One-To-One relationship
In the below example, we will create a User Details entity, and we assume each user can have ONLY one vehicle.

1).
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "vehicle_details")
public class Vehicle {
    @Id @GeneratedValue
    private int vehicleId;
    private String vehicleName;

    public int getVehicleId() {
        return vehicleId;
    }
    public void setVehicleId(int vehicleId) {
        this.vehicleId = vehicleId;
    }
    public String getVehicleName() {
        return vehicleName;
    }
    public void setVehicleName(String vehicleName) {
        this.vehicleName = vehicleName;
    }
}

2).
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "user_details")
public class UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int userid;
    private String userName;
    @OneToOne
    @JoinColumn(name="vehicle_id_fk")
    private Vehicle vehicle;
    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public Vehicle getVehicle() {
        return vehicle;
    }
    public void setVehicle(Vehicle vehicle) {
        this.vehicle = vehicle;
    }
}

3).
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class UserOneToOneMappingTest {
    public static void main(String[] args) {
        Vehicle vehicle=new Vehicle();
        vehicle.setVehicleName("Mercedes Benz");
        UserDetails userDetails=new UserDetails();
        userDetails.setUserName("Andrew Matthews");
        userDetails.setVehicle(vehicle);
       
        // create a session factory
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        // get the session from session factory
        Session savesession = sessionFactory.openSession();
        savesession.beginTransaction();
        // to save the object in hibernate
        savesession.save(userDetails);
        savesession.save(vehicle);
        savesession.getTransaction().commit();
        savesession.close();
    }
}


When you execute UserOneToOneMappingTest class, user_details and vehicle_details are created. User details are inserted in user_details, after that vehicle details are inserted in vehicle_details, later vehicle_id_fk is updated in user_details table.

Hibernate: select next value for hibernate_sequence
Hibernate: select next value for hibernate_sequence
Hibernate: insert into user_details (userName, vehicle_id_fk, userid) values (?, ?, ?)
Hibernate: insert into vehicle_details (vehicleName, vehicleId) values (?, ?)
Hibernate: update user_details set userName=?, vehicle_id_fk=? where userid=?


If you save vehicle first and then userDetails, then vehicle details are inserted in vehicle_details and then User details are inserted in user_details, along with vehicle id (update query is not fired).

If you have not saved the user by calling save on vehicle object 'savesession.save(vehicle)', then you will get an error message:
'object references an unsaved transient instance - save the transient instance beforeQuery flushing: com.onetoone.mapping.Vehicle'

 Example of One-To-Many relationship
In the below example, we will create a User Details entity, and each user can have multiple vehicle.
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

1).
@Entity
@Table(name = "vehicle_details")
public class Vehicle {
    @Id @GeneratedValue
    private int vehicleId;
    private String vehicleName;

    //getters and setters
}
2).
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "user_details")
public class UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int userid;
    private String userName;
    @OneToMany
    @JoinTable(joinColumns=@JoinColumn(name="user_id_fk"),
              inverseJoinColumns=@JoinColumn(name="vehicle_id_fk"))
    private Collection < Vehicle > vehicle=new ArrayList < Vehicle > ();
    //getters and setters
}

3).
public class UserOneToManyMappingTest {
    public static void main(String[] args) {
        Vehicle vehicle1=new Vehicle();
        vehicle1.setVehicleName("Mercedes Benz");
        Vehicle vehicle2=new Vehicle();
        vehicle2.setVehicleName("Lamborghini");
        UserDetails userDetails=new UserDetails();
        userDetails.setUserName("K Himaanshu Shuklaa");
        userDetails.getVehicle().add(vehicle1);
        userDetails.getVehicle().add(vehicle2);
       
        // create a session factory
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        // get the session from session factory
        Session savesession = sessionFactory.openSession();
        savesession.beginTransaction();
        // to save the object in hibernate       
        savesession.save(vehicle1);
        savesession.save(vehicle2);
        savesession.save(userDetails);
        savesession.getTransaction().commit();
        savesession.close();
    }
}

When you execute UserOneToManyMappingTest class, following queries will be fired:
Hibernate: insert into vehicle_details (vehicleName, vehicleId) values (?, ?)
Hibernate: insert into vehicle_details (vehicleName, vehicleId) values (?, ?)
Hibernate: insert into user_details (userName, userid) values (?, ?)
Hibernate: insert into user_details_vehicle_details (user_id_fk, vehicle_id_fk) values (?, ?)
Hibernate: insert into user_details_vehicle_details (user_id_fk, vehicle_id_fk) values (?, ?)

May 05, 2017

RSSChomp Blog Directory