Wednesday, September 5, 2012

Step By Step Hibernate with Netbeans



You can easily create hibernate application with Netbeans.

  1. First create database. I use command line with following command.


Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Masudul Haque>mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.5.8 MySQL Community Server (GPL)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database library;
Query OK, 1 row affected (0.04 sec)

mysql> create user cuet@localhost;
Query OK, 0 rows affected (0.20 sec)

mysql> grant all on library.* to cuet@localhost identified by 'cuet';
Query OK, 0 rows affected (0.04 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.09 sec)

mysql>

  1. In my netbeans IDE I create a project named 'library_management'
  2. Create a hibernate configuration by following way.


  1. Then I show the my Mysql database connection by clicking next.



  1. After verify my connection is success I click finish. With this attempt hibernate.cfg.xml file will be created. Following is my hibernate.cfg.xml file.
            <?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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
                <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
                <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/library?zeroDateTimeBehavior=convertToNull</property>
                <property name="hibernate.connection.username">cuet</property>
                <property name="hibernate.connection.password">cuet</property>
                
                <mapping class="edu.cuet.library.model.Student"/>
                
              </session-factory>
            </hibernate-configuration>
             
            6. To perform any operation is hibernate you should have Hibernate SessionFactory class. Using netbeans you can easily generate SessionFactory class. From project you should click new to other and under hibernate section you should select HibernateUtil.java then click finish. Following is the HibernateUtil.java file

          /*

           * To change this template, choose Tools | Templates
           * and open the template in the editor.
           */
          package edu.cuet.library.util;

          import org.hibernate.cfg.AnnotationConfiguration;
          import org.hibernate.SessionFactory;

          /**
           * Hibernate Utility class with a convenient method to get Session Factory
           * object.
           *
           * @author Masudul Haque
           */
          public class HibernateUtil {

              private static final SessionFactory sessionFactory;
             
              static {
                  try {
                      // Create the SessionFactory from standard (hibernate.cfg.xml)
                      // config file.
                      sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
                  } catch (Throwable ex) {
                      // Log the exception.
                      System.err.println("Initial SessionFactory creation failed." + ex);
                      throw new ExceptionInInitializerError(ex);
                  }
              }
             
              public static SessionFactory getSessionFactory() {
                  return sessionFactory;
              }
          }




          Creating POJO class:
          1. Following is my domain class.

          /*

           * To change this template, choose Tools | Templates
           * and open the template in the editor.
           */
          package edu.cuet.library.model;

          import java.util.Date;
          import javax.persistence.Column;
          import javax.persistence.Entity;
          import javax.persistence.GeneratedValue;
          import javax.persistence.GenerationType;
          import javax.persistence.Id;
          import javax.persistence.Temporal;
          import javax.persistence.TemporalType;

          /**
           *
           * @author Masudul Haque
           */
          @Entity
          public class Student {
              @Id
              @GeneratedValue(strategy= GenerationType.AUTO)
              private Long id;    
              @Column(name="student_id",length=7)
              private String studentId;
              @Column(name="first_name",length=50)
              private String firstName;
              @Column(name="last_name",length=50)
              private String lastName;
              @Temporal(TemporalType.DATE)
              private Date birthDate;

              public Long getId() {
                  return id;
              }

              public void setId(Long id) {
                  this.id = id;
              }

              public String getStudentId() {
                  return studentId;
              }

              public void setStudentId(String studentId) {
                  this.studentId = studentId;
              }

              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 Date getBirthDate() {
                  return birthDate;
              }

              public void setBirthDate(Date birthDate) {
                  this.birthDate = birthDate;
              }
              
          }


          DB Export:
          1. It is really easy to export database export from POJO class. For that you need to map domain class to hibernate.cfg.xml on following way.
                         

                                 
             
          1. Write a application file with named DBExport with following code.


          /*

           * To change this template, choose Tools | Templates
           * and open the template in the editor.
           */
          package edu.cuet.library.database;

          import org.hibernate.cfg.AnnotationConfiguration;
          import org.hibernate.tool.hbm2ddl.SchemaExport;

          /**
           *
           * @author Masudul Haque
           */
          public class DBExport {

              /**
               * @param args the command line arguments
               */
              public static void main(String[] args) {
                  AnnotationConfiguration conf= new AnnotationConfiguration();
                  conf.configure();
                  SchemaExport export=new SchemaExport(conf);
                  export.execute(true, true, false, true);
              }
          }


          1. After that run the application and database structure will be generated from POJO class.

          Introduction to Java


          WHEN YOU BEGIN a journey, it's a good idea to have a mental map of the terrain you'll be passing through. The same is true for an intellectual journey, such as learning to write computer programs. In this case, you'll need to know the basics of what computers are and how they work. You'll want to have some idea of what a computer program is and how one is created. Since you will be writing programs in the Java programming language, you'll want to know something about that language in particular and about the modern, networked computing environment for which Java is designed.

          The Java programming language is a high-level language that can be characterized by all of the following buzzwords:
          • Simple
          • Object oriented
          • Distributed
          • Multithreaded
          • Dynamic
          • Architecture neutral
          • Portable
          • High performance
          • Robust
          • Secure
          Each of the preceding buzzwords is explained in The Java Language Environment , a white paper written by James Gosling and Henry McGilton.
          In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by thejavac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine1 (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine.
          Figure showing MyProgram.java, compiler, MyProgram.class, Java VM, and My Program running on a computer.
          An overview of the software development process.

          Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris™ Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java SE HotSpot at a Glance, perform additional steps at runtime to give your application a performance boost. This include various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code.
          Figure showing source code, compiler, and Java VM's for Win32, Solaris OS/Linux, and Mac OS
          Through the Java VM, the same application is capable of running on multiple platforms.




          Tuesday, September 4, 2012

          Introduction of Spring Framework


          The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.
          Spring includes:
          • Flexible dependency injection with XML and annotation-based configuration styles
          • Advanced support for aspect-oriented programming with proxy-based and AspectJ-based variants
          • Support for declarative transactions, declarative caching, declarative validation, and declarative formatting
          • Powerful abstractions for working with common Java EE specifications such as JDBC, JPA, JTA and JMS
          • First-class support for common open source frameworks such as Hibernate and Quartz
          • A flexible web framework for building RESTful MVC applications and service endpoints
          • Rich testing facilities for unit tests as well as for integration tests

          Spring is modular in design, allowing for incremental adoption of individual parts such as the core container or the JDBC support. While all Spring services are a perfect fit for the Spring core container, many services can also be used in a programmatic fashion outside of the container.
          Supported deployment platforms range from standalone applications to Tomcat and Java EE servers such as WebSphere. Spring is also a first-class citizen on major cloud platforms with Java support, e.g. on Heroku, Google App Engine, Amazon Elastic Beanstalk and VMware's Cloud Foundry.
          The Spring Framework serves as the foundation for the wider family of Spring open source projects, including:
          • Spring Security
          • Spring Integration
          • Spring Batch
          • Spring Data
          • Spring Web Flow
          • Spring Web Services
          • Spring Mobile
          • Spring Social
          • Spring Android