Wednesday, June 4, 2014

Hibernate sample code save()



This is the Hibernate sample code which inserts a record set into a table.
Create a Java project HibernateCRUDSampel in Eclipse project explorer.

1.    Create a folder structure.



2.    Create hibernate.cfg.xml. 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
      <session-factory>
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
            <property name="connection.url">jdbc:mysql://localhost/testapp</property>
            <property name="connection.username">root</property>
            <property name="connection.password">password</property>
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="connection.show_sql">true</property>
            <mapping resource="resource/Student.hbm.xml" />
      </session-factory>
</hibernate-configuration>
 

3.    Create a Student mapping file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
      <class name="sample.hiber.crud.model.Student" table="student">
            <id name="studentId" type="java.lang.Integer">
                  <column name="student_id" />
                  <generator class="identity" />
            </id>
            <property name="regNo" type="java.lang.Long">
                  <column name="reg_no" />
            </property>
            <property name="firstName" type="string">
                  <column name="first_name" />
            </property>
            <property name="lastName" type="string">
                  <column name="last_name" />
            </property>
            <property name="age" type="java.lang.Integer">
                  <column name="age" />
            </property>
            <property name="sex" type="java.lang.Character">
                  <column name="sex" />
            </property>
            <property name="mailId" type="string">
                  <column name="mail_id" />
            </property>
            <property name="mobileNo" type="string">
                  <column name="mobile_no" />
            </property>
      </class>
</hibernate-mapping>
 

 

4.    Create a table student in MySQL with following structure





5.    Create a mapping object Class Student.java


public class Student implements Serializable{

      private static final long serialVersionUID = -1097973765295431159L;
      private int studentId;
      private long regNo;
      private String firstName;
      private String lastName;
      private int age;
      private char sex;
      private String mailId;
      private String mobileNo;
      // Constructor
      public Student() {
      }
      // Constructor
      public Student(int studentId, long regNo, String firstName,
                  String lastName, int age, char sex, String mailId, String mobileNo) {
            this.studentId = studentId;
            this.regNo = regNo;
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
            this.sex = sex;
            this.mailId = mailId;
            this.mobileNo = mobileNo;
      }
      public int getStudentId() {
            return studentId;
      }
      public void setStudentId(int studentId) {
            this.studentId = studentId;
      }
      public long getRegNo() {
            return regNo;
      }
      public void setRegNo(long regNo) {
            this.regNo = regNo;
      }
      public String getFirstName() {
            return firstName;
      }
      public void setFirstName(String firstName) {
            this.firstName = firstName;
      }
      public String getLastName() {
            return lastName;
      }
      public void setLastName(String lastName) {
            this.lastName = lastName;
      }
      public int getAge() {
            return age;
      }
      public void setAge(int age) {
            this.age = age;
      }
      public char getSex() {
            return sex;
      }
      public void setSex(char sex) {
            this.sex = sex;
      }
      public String getMailId() {
            return mailId;
      }
      public void setMailId(String mailId) {
            this.mailId = mailId;
      }
      public String getMobileNo() {
            return mobileNo;
      }
      public void setMobileNo(String mobileNo) {
            this.mobileNo = mobileNo;
      }
      public static long getSerialversionuid() {
            return serialVersionUID;
      }

}

6.    Create class to run the sample application


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

import sample.hiber.crud.model.Student;

public class MainTest {
      private static SessionFactory factory;

      public static void main(String[] args) {
      MainTest m = new MainTest();
      try {
            factory = new Configuration().configure().buildSessionFactory();
      } catch (Throwable ex) {
      System.err.println("Failed to create sessionFactory object." + ex);
      throw new ExceptionInInitializerError(ex);
      }
      m.addStudent(new Student(1012012, 123123123l, "John", "Peter", 35, 'M',
      "pjohn@gmai.com", "5678902324"));
      }

      private void addStudent(Student s) {
            Session session = factory.openSession();
            session.beginTransaction();
            session.save(s);
            session.flush();
            session.getTransaction().commit();
            session.close();
      }

}


Spring's IoC and Template method Pattern

Why Spring Uses Template Method Pattern?

As Spring technology configures, instantiates and maintains objects in IoC container  as beans injects them into needed dependent beans.
And Template Method Pattern is Mother of all Frameworks, and components in SpringFramework. Spring and its all Template components like JDBC Template, JMS Template are instantiating beans in the same way. Also let developer to extend them.


What is Template Method Pattern?
The template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets programmer redefine certain steps of an algorithm without changing the algorithm's structure.
If we declare a abstract class or framework it has to perform some operations, we declare all methods one method which call all the other methods to perform a respective operation.
Like if we have a class EmployeeRegister and which serves users registerEmployee() and to register employee we have to perform following three operations like
getEmployeeDetails()
generateNewRegNo()
registerNewEmployee().
These methods are abstract and let users to override. But we let the user to call only one method from outside registerEmployee().

EmployeeDO registerEmployee()
{

getEmployeeDetails();
generateNewRegNo();
registerNewEmployee();

}
So when implementing this abstraact class we have to override the these methods.
Finally this pattern let users to perform the registering also let him to override the methods.In simple words make a class "Open for Extension but closed for Modification"
like here we can extend how to do registration but not able to modify the steps.

What is Ioc?
           " Do not call me ! I will call you ! ".
First we will see the problem of "Tight Coupling".
class Customer()
{
private Address address;
private AccountDetails accountDetails;

Customer()
{
address = new Address();
accountDetails = new AccountDetails():
}
}

Here the problem is creation of instances of Address and AccountDetails.It is fully depends on Customer. So it is tighly coupled.
Now that we know the issue, let’s understand the solution. The solution definitely revolves around shifting the object creation control from the customer class to some one else. Solution comes with concept IoC it resolves the instantiating the objcets and looses the objects from other. So objects are instantiated individually at common place called IoC container and shared across beans though DI process.
And they are injected to the classes which calls them. Like in our case Address and AccountDetails are instantiated and injected to Customer instance this process called as Dependency Injection.

What are all the templates uses this Pattern?

As Spring let the users to extend its all components like JDBC Template, JMS Template, etc.,. uses this same method.
They declares its abstract components, developers have to implement them by extending. He cant modify the steps but have to extend and override the methods.
Also Spring uses all instantiating are maintained as beans created at common place and injected to other beans.


Template method Pattern and Spring Framework

Why Spring Uses Template Method Pattern?

As Spring technology configures, instantiates and maintains objects in IoC container  as beans injects them into needed dependent beans.
And Template Method Pattern is Mother of all Frameworks, and components in SpringFramework. Spring and its all Template components like JDBC Template, JMS Template are instantiating beans in the same way. Also let developer to extend them.


What is Template Method Pattern?
The template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets programmer redefine certain steps of an algorithm without changing the algorithm's structure.
If we declare a abstract class or framework it has to perform some operations, we declare all methods one method which call all the other methods to perform a respective operation.
Like if we have a class EmployeeRegister and which serves users registerEmployee() and to register employee we have to perform following three operations like
getEmployeeDetails()
generateNewRegNo()
registerNewEmployee().
These methods are abstract and let users to override. But we let the user to call only one method from outside registerEmployee().

EmployeeDO registerEmployee()
{

getEmployeeDetails();
generateNewRegNo();
registerNewEmployee();

}
So when implementing this abstraact class we have to override the these methods.
Finally this pattern let users to perform the registering also let him to override the methods.In simple words make a class "Open for Extension but closed for Modification"
like here we can extend how to do registration but not able to modify the steps.

What is Ioc?
           " Do not call me ! I will call you ! ".
First we will see the problem of "Tight Coupling".
class Customer()
{
private Address address;
private AccountDetails accountDetails;

Customer()
{
address = new Address();
accountDetails = new AccountDetails():
}
}

Here the problem is creation of instances of Address and AccountDetails.It is fully depends on Customer. So it is tighly coupled.
Now that we know the issue, let’s understand the solution. The solution definitely revolves around shifting the object creation control from the customer class to some one else. Solution comes with concept IoC it resolves the instantiating the objcets and looses the objects from other. So objects are instantiated individually at common place called IoC container and shared across beans though DI process.
And they are injected to the classes which calls them. Like in our case Address and AccountDetails are instantiated and injected to Customer instance this process called as Dependency Injection.

What are all the templates uses this Pattern?

As Spring let the users to extend its all components like JDBC Template, JMS Template, etc.,. uses this same method.
They declares its abstract components, developers have to implement them by extending. He cant modify the steps but have to extend and override the methods.
Also Spring uses all instantiating are maintained as beans created at common place and injected to other beans.