Hibernate


Basic  Hibernate Installation Steps with Eclipse in Windows 7 and Its Workout

Step -1

Step 2

 Then Download Hibernate Source and jar files from http://sourceforge.net/projects/hibernate/files/hibernate4/ 

Step 3

Assure that you have JDK 1.7 and Tomcat 7 installed in Eclispe. If not Go to
Window => Preferences =>
onLeft Tab Select Server => Now Select Runtime Enviroment => Click Add
 => Select Apache Tomcat 7 => Now Select Download and Install => Select Drive to get tomcat downloaded into.
Note :- Since we are not going to learn Hibernate initially with Jsp/Servlet for now, so we donot require Apache Tomcat Server so you may Ignore installing it for Now.



Hello World With Hibernate

So Far we have installed hibernate now lets Start Development. Remember MVC makes code better so chill I will drive you smoothly and make you feel comfortable with code.

Step 1

Open Eclipse File -> New -> JavaProject -> Finish

Step 2

Right Click on your Project -> Goto Properties -> Select Java Build Path -> Select Add Library
-> Select User Library -> Click on User Libraries -> Select New -> Enter Library Name(Keep Hibernate as Name) -> Dont Check the Check Box -> Just Click Ok.
Now Goto  Add Jars (Select Following Jars from the Hibernate)
Source of Hibernate You have downloaded contains lib folder into it.
LIB [It has 4 sub Folders ]
 |-envers
 |-Jpa
 |-optional
 |-required
Add All Jars from required Folder all jars from Jpa folder and all jars from envers folder.

Step 3

Since You are creating an JDBC connection so you also need an Database, Here i am Using Postgresql you get it downloaded from
so you need a Jdbc jar file type jdbc jar file for postgres, In case if you are using other database then type your database name instead of postgressql.

Step 4

copy paste jar file into eclipse under your Project, Right Click on jar file -> select build path -> select configure build path
example
Project Name
|-- postgres-jdbc-jar
perform above give steps on this jar file

Step 5

Now Create a file in src folder named hibernate.cfg.xml and copy all the below code





    

        
        
        org.postgresql.Driver
        jdbc:postgresql://localhost:5433/Hibernate_First
        postgres
        root

        
        1

        
        org.hibernate.dialect.PostgreSQLDialect
        
        org.hibernate.cache.NoCacheProvider
        true
        create

        
        
    

Step 6

Now create a package com.test.dto in src folder and create com.test.main so after creating packages
It looks something like this
src
 |-- com.test.dto
 |-- com.test.main
 |-- hibernate.cfg.xml

Step 7

create  a new Class File under Package com.test.dto
User.Java
package com.test.main;

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

import com.test.hibernate.dto.UserDetail;
import com.test.hibernate.dto.Address;

public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  User userDetail = new User();
  userDetail.setUserName("First User");
//Note here you dont need to provide Id @GeneratedValue takes care of it in User.java class
  
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  
  try {
  
  session.beginTransaction();
  session.save(userDetail);
  session.getTransaction().commit();
  session.close();

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

 
Create another Java file  into com.test.main Package
Main.java
package com.test.dto;

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
 
 @Id @GeneratedValue(strategy=GenerationType.AUTO) 
 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;
 }
 
}
 

Step 8

Now goto Database and fire query
select * from User;
you will see data.
!Njoy your First Ride to Hibernate :)

Tips :-

=> Create SessionFactory
=> Create Session From Session Factory
=> Use session to save objects
In hibernate.cfg.xml file we have a property hbm2ddl.auto is set to major. i.e it creates a new table with name of class.

Hibernate Configuration File

Understanding hibernate.cfg.xml in detail

Hibernate Properties

S.N.

Properties and Description

1

hibernate.dialect
This property makes Hibernate generate the appropriate SQL for the chosen database.

2

hibernate.connection.driver_class
The JDBC driver class.

3

hibernate.connection.url
The JDBC URL to the database instance.

4

hibernate.connection.username
The database username.

5

hibernate.connection.password
The database password.

6

hibernate.connection.pool_size
Limits the number of connections waiting in the Hibernate database connection pool.

7

hibernate.connection.autocommit
Allows autocommit mode to be used for the JDBC connection.
If you are using database along with application server and database then configure following properties

S.N.

Properties and Description

1

hibernate.connection.datasource
The JNDI name defined in the application server context you are using for the application.

2

hibernate.jndi.class
The InitialContext class for JNDI.

3

hibernate.jndi.<JNDIpropertyname>
Passes any JNDI property you like to the JNDI InitialContext.

4

hibernate.jndi.url
Provides the URL for JNDI.

5

hibernate.connection.username
The database username.

6

hibernate.connection.password
The database password.



Hibernate Annotations

Since in our first program of hello world we have used two annotations @Entity @Id and @GeneratedValue
Now let us focus on few amaizing and impotant annotations that makes hibernate more Juicy :) .

package com.test.hibernate.dto;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.Table;

@Entity
@Table(name="MyTable")  //New
public class UserDetail {
 
 @Id
        @GeneratedValue(strategy=GenerationType.AUTO) 
 @column(name="User_Id") //New
        private int userId;
        @Temporal (TemporalType.DATE)
        private Date joinedDate;

        @column(name="User_Name") //New
 private String userName;
 
 
 public void setUserId(int userId) {
  this.userId = userId;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
        public void setJoinedDate(Date joinedDate) {
                this.joinedDate = joinedDate;
        }
        public Date getJoinedDate() {
               return joinedDate;
        }

 
}

@Entity @Table
 Here @Entity automatically creates a name for table in database. So far consider you don't want Table name same as class name, then you can specify the name Attribute in @Table or @Entity, and change the name as done in above example

@column
 By default Hibernate creates column based on name of attributes but suppose you want to change name of column then above attribute write annotation @column(name="colName").

@Temporal (TemporalType.DATE)
 Joined date attribute is Date type so it saves Data & Time now if we only want to store Date then we need to use TemporalType.DATE
  
@Lob
Large Object Binary is used in fields like Address or other descreptive fields, where user name exceed the default range. For Binary Type it has BLOB and for character type it had CLOB
one can use any of it as per necessity.

There are also many other use-ful annotations, we will look at it once we complete reterival and Mappings (one-one, one-many, many-one, many-many).



Data-Retrival in Hibernate

So far we have seen Data Insertion in hibernate now in this example we will get some simple steps regarding Data-Retrival.

Main.java
package com.test.hibernate;

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

import com.test.dto.User;

public class HibernateTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  UserDetail userDetail = new UserDetail();
  userDetail.setUserName("First User");

  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  
  try {
  
  session.beginTransaction();
  session.save(userDetail);
  session.getTransaction().commit();
  session.close();

  //Here it teaches us about early aand late object binding
  userDetail = null;
  session = sessionFactory.openSession();
  userDetail = (UserDetail)session.get(UserDetail.class, 1);
                /*
                 *Here it passes UserDetail class in get method in session and pass '1',
                 *1 is id so it acts something like this, Record with Id 1 from User Entity
                 */
  session.close();
                 System.out.println("User Name :=>"+userDetail.getUserName()); 
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
  
 }

}


Gotya :). In case we need a whole data then we need to write loops and instead of passing 1 we need to pass dynamic variable.


Attributes within Attribute (Embedded Objects)

Consider we have an User class with Id, Name, Address, Phone, Date of Birth.
-> Now Address Filed can have sub-Attributes like street, city, state, pincode.
so we can break it down in to another sub-attributes and it looks like.
Now when we will embed this atrributes it will create an another entity, i.e. in simple terms we will create a table with following fields id, name, street, city, state, pincode, phon, DOB. Two Seperate Entities will be created and then by merging them as embedable we will get following Result.

Embeddable Example

User.java

package com.test.dto;

import java.util.Date;

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="User_Details")
public class User {

 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private int user_Id;
 private String Name;
 private String phone;
 private Date DOB;
 
 /*
  * @Embedded
  * It specifies  that Address Class is Embeddable and so it can be Embedded using this annotation.
  * At execution time you simply need to create a seperate Address Object and finally set That object into user class 
  * using setter method for Address in this class. 
  */
 
 @Embedded
 private Address address;
 
 public Address getAddress() {
  return address;
 }
 public void setAddress(Address address) {
  this.address = address;
 }
 //Getters and Setters for User Class
 
 public String getName() {
  return Name;
 }
 public void setName(String name) {
  Name = name;
 }
 public String getPhone() {
  return phone;
 }
 public void setPhone(String phone) {
  this.phone = phone;
 }
 public Date getDOB() {
  return DOB;
 }
 public void setDOB(Date dOB) {
  DOB = dOB;
 }
 public int getUser_Id() {
  return user_Id;
 }
 public void setUser_Id(int user_Id) {
  this.user_Id = user_Id;
 }
 
}

Here, in user class we have created a id, name, dob etc Along With Address object. This Address attribute it Self is an Class and will act as an Attribute in User classs.
The @Embedded attribute will appped all the attributes of Address Class into User class run-time.

Now Lets look How Address Class can be written .

Address.java
/*
 * This class is created with No Entity and Id Attribute as It will be Embedded in to some other Emtity
 * @Embeddable Annotation means that this class is not an Entity but it is Embeddable kind of class so it will get 
 * Embedded into some Other class
 * Note :- To Embeded it into another class Just write 
 * @Embedded above its object. 
 */
package com.test.dto;

import javax.persistence.Embeddable;

@Embeddable 
public class Address {

 private String street;
 private String state;
 private String city;
 private String pincode;
 
 //Getters and Setter For Address Class
 public String getStreet() {
  return street;
 }
 public void setStreet(String street) {
  this.street = street;
 }
 public String getState() {
  return state;
 }
 public void setState(String state) {
  this.state = state;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getPincode() {
  return pincode;
 }
 public void setPincode(String pincode) {
  this.pincode = pincode;
 }
 
 
}

As said the Address class is made Embeddable rather than an seperate entity so that its attributes can be appended into other Entity.
Finally, MainClass that stores Object and makes it embeddedable.

MainClass.java

package com.test.main;

import java.util.Date;

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

import com.test.dto.User;
import com.test.dto.Address;

public class MainClass {

 public static void main(String a[])
 {
  User user = new User();
  Address address  = new Address();
  
  user.setName("user_name");
  user.setPhone("000000000");
  
  // Now add data into Address Object and set Address to User
  
  address.setStreet("Street");
  address.setCity("City");
  address.setState("State");
  address.setPincode("123456");

  //Now set this address to user so it will get Embedded to User Entity
  user.setAddress(address);
  try 
  {
   @SuppressWarnings("deprecation")
   SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
   Session session = sessionFactory.openSession();
   session.beginTransaction(); 
   
   session.save(user);
   
   session.getTransaction().commit();
   session.close();
  }catch(Exception e)
  {
   e.printStackTrace();
  }
  
 }
}
Here in main class we have created an User object and Address object so that we can set all its Attributes, As declared we have an Address Attribute in User class so by injecting
user.setAddress(address); 

we actually are injecting Address attributes i.e(city,state,pincode,street) into User class. Njoy!


Consider we have Address 1 and Address 2 for Particular Address then how could we achieve this using above single Address class.

AttributeOverrides and Embeddable


 

No comments:

Post a Comment