Hibernate Introduction Part 4

 

This article is a continuation of our previous article.

In the previous post, we have seen how to retrieve all the records in the database. But most of time, this is not the case.  Sometime we need to retrieve particular record by passing the primary key.

Say for example, in SQL

Select * from User where UserID=’John’

This can be achieved in HQL using Variable injection option

And also , When we expect multiple rows, then we know what we can use Query’s List method() as we seen in the previous example. On the other hand, When we expect a single record, then we can use Query’s  uniqueResult()

 

Here is the full code for the Method to retrieve the unique record

 

public static void getPatientByID(int anyvalue) {

    try {
        Configuration configuration = new Configuration();
        configuration.configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(
                configuration.getProperties()).buildServiceRegistry();
        factory = configuration.buildSessionFactory(serviceRegistry);
    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex);
    }
    System.out.println("**Example : Hibernate  SessionFactory**");
    System.out.println("----------------------------------------");
   
    Session session = factory.openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        Query q1 = session.createQuery("from patient where id =:idvalue");
        q1.setInteger("idvalue", anyvalue);
        Object queryResult = q1.uniqueResult();
        patient p1 = (patient)queryResult;
        tx.commit();
        System.out.print(p1.getLastName());
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
}

 

Here is the updated test.java code

package mypack;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.HibernateException;

public class Test {

    private static SessionFactory factory;
    private static ServiceRegistry serviceRegistry;

    public static void main(String[] args) {
        createRecords();
        getAllRecords();
        getPatientByID(1);
        getPatientByID(13);
       
    }

    public static void createRecords() {

        try {
            Configuration configuration = new Configuration();
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).buildServiceRegistry();
            factory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
        System.out.println("**Example : Hibernate 4 SessionFactory**");
        System.out.println("----------------------------------------");

        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            patient pt = new patient();
            pt.setFirstName("John12");
            pt.setLastName("Smith23");
            session.saveOrUpdate(pt);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
   
    public static void getAllRecords() {

        try {
            Configuration configuration = new Configuration();
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).buildServiceRegistry();
            factory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
        System.out.println("**Example : Hibernate  SessionFactory**");
        System.out.println("----------------------------------------");
       
        List allpatients;
       
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Query q1 = session.createQuery("from patient");
            allpatients = q1.list();
            for (int i =0; i < allpatients.size(); i++)
            {
                patient pt = (patient) allpatients.get(i);
                System.out.println(pt.getLastName());
            }
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

   
    public static void getPatientByID(int anyvalue) {

        try {
            Configuration configuration = new Configuration();
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).buildServiceRegistry();
            factory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
        System.out.println("**Example : Hibernate  SessionFactory**");
        System.out.println("----------------------------------------");
       
       
       
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Query q1 = session.createQuery("from patient where id =:idvalue");
            q1.setInteger("idvalue", anyvalue);
            Object queryResult = q1.uniqueResult();
            patient p1 = (patient)queryResult;
            tx.commit();
            System.out.print(p1.getLastName());
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

}

ZK Data Binding Part 1

 

Before seeing the ZK Data binding concept , first let us learn the for each attribute in zk

The following zul file is simple which has the list items

<?page title="Example1" contentType="text/html;charset=UTF-8"?>
<zk>
    <window title="Example1" border="normal">
        Example for "for each"
        <listbox>
            <listitem label="Apple" />
            <listitem label="Orange" />
            <listitem label="Strawberry" />
        </listbox>
    </window>
</zk>

image

The output can be expected if you use for each attribute as follows

 

<?page title="Example2" contentType="text/html;charset=UTF-8"?>
<zk>
    <window title="Example2" border="normal">
        Example for "for each"
        <listbox>
            <listitem label="${each}"
                forEach="Apple, Orange, Strawberry" />
        </listbox>
    </window>
</zk>

 

The forEach attribute is used to specify a collection of object such that the XML element it belongs will be evaluated repeatedly for each object of the collection.

Simple Sightseeing Application Part 2



In the part 1, we have seen how to work on sight seeing application locally by having some
static values. In this part, we will see how we can connect to the database using hibernate and
retrive the values from the table

Window CSS

ZK Simple Sightseeing Application Part 1


After reading the following article,
http://books.zkoss.org/wiki/ZK_Getting_Started/Creating_a_Simple_Sightseeing_Application

I decided to connect with the DB and to make database driven application.

Button CSS

 
 
All
ZK Button CSS
 

Group Box with Collapse and Expand Button in the Right

Group Box with Collapse and Expand Button in the Right

Tuning Eclipse Performance and Avoiding OutOfMemoryExceptions



If you are using 4 GB Ram, the following will help you to increase the speed of the eclipse

Goto the Folder where eclipse.exe is located.

Open the eclipse.ini


-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20110502
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vm
C:/Program Files/Java/jdk1.6.0_21/bin/javaw
-vmargs
-Xmn128m
-Xms1024m
-Xmx1024m
-Xss2m
-XX:PermSize=128m
-XX:MaxPermSize=128m
-XX:+UseParallelGC


For other than 4 GB, read the following article



http://madhucm.wordpress.com/2007/12/19/tuning-eclipse-performance-and-avoiding-outofmemoryexceptions/


Listitem Mold Paging - Add components in the pagination bar


<zk>
 <zscript>
  Object[] o = new Object[50];
 </zscript>
 <toolbar>
  <hlayout sclass="z-valign-middle">
   <toolbarbutton label="other button 1"></toolbarbutton>
   <paging id="pagenavi" pageSize="10"></paging>
   <toolbarbutton label="other button 2"></toolbarbutton>
  </hlayout>
 </toolbar>
 <listbox id="listbox" mold="paging" paginal="${pagenavi}">
  <listhead>
   <listheader label="name"></listheader>
  </listhead>
  <listitem forEach="${o}">
   <listcell label="item ${forEachStatus.index}" />
  </listitem>
 </listbox>
</zk>

For more information, please refer the following thread
http://www.zkoss.org/forum/listComment/19535-Listbox-mold-paging

ZK Calling Another ZUL File

Method 1


<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
<window title="new page title" border="normal">
New Content Here!
<button label="click me" href="../main/Practice.zul"/>
</window>
</zk>


Method 2


<zk>
  <window id="mainwin" border="normal" title="hello" xmlns:c="client">
 
  <button label="Practice">
          <attribute name="onClick">
            Executions.createComponents("../main/Practice.zul",mainwin,null);
          </attribute>
    </button>
  </window>
</z

ZK Installation Guide


Part 1.
Explains how to setup java, maven, Tomcat and Eclipse IDE. You can download the document here.

Part 2
Explains how to setup ZK Studio and ZK CE Version. You can download the document here.

Part 3
Explains how to download and setup ZK Sample 2 application locally. You can download the document here.


 

Eclipse Tips and Tricks

1. External Browser

Whenever you run the application, you can see the output using internal browser. By normally i will not prefer that method. So you can change the settings, to open the output using any external browser

Here is the steps

1. Click Window -> Preferences-> General-> Web Browser
    Change to External web Browser. Choose from the list. Here my choice is fire fox


Hibernate Introduction Part 3


Data query.


Well, Now we will see how to query all the records inserted into the database that we have done
in part 1 and part 2.

For all the future examples (including this), i am going use only JPA Annotations

let's start.

Step 1: Development environment

1. My sql server 5.0  Download
2. Hibernate 4.1.1 Download
3. JDBC Driver for Mysql ((mysql-connector-java-5.1.19.zip)) Download
4. Eclipse IDE

Unzip the hibernate buddle and you should have the following structure after you unzip
Documentation folder
lib Folder
Project folder
log text file
hibernate logo image
license text file


Step 2:

Open mysql and create the following table in any of the exisitng database or create new database.
Here is the script for our table


CREATE TABLE `patient`
 (
    `ID` INT(11) NOT NULL AUTO_INCREMENT,
    `FirstName` VARCHAR(100) DEFAULT NULL,
    `LastName` VARCHAR(100) DEFAULT NULL,
    `Email` VARCHAR(200) DEFAULT NULL,
     PRIMARY KEY  (`ID`)
 )  ENGINE=INNODB DEFAULT


Step 3: Eclipse Java project

1. Click File -> New -> Other -> Java Project

2. Say Example3 for Project Name and leave all other to default values.
   (Make sure, JRE has been configured).

3. Next we will add all dependencies in the example3. Now click Example3 project in the project
   explorer and right click -> Click New-> Folder. Say folder name as lib

   Now copy the following files into lib folder
   (Note : Eclipse project explorer accepts all copy and paste operation. For example, you can copy    

   file or folder in windows explorer and then you can come back to eclipse project explorer and paste

  it)

   All the files in Hibernate->Lib->required.
   All the files in Hibernate->Lib->jpa.
   All the files in Hibernate->Lib->envers
   mysql-connector-java-5.1.18-bin.jar


4. Now  setup the build path. In order to execute our example, all the above jar files should be in
   class build path

   Again, click on the Example1, right click, and select build Path->configure build path.
   Go to Libraries-> External jars,  browse lib folder you created earlier. Then add external jars by
   selecting all jar files that you copied to lib folder in one of previous step


Step 4: Creating Java beans

Now let us create the java bean for the patient where we want to store in the database.

Again, right click on Example1, Select New -> Class; Package Name : mypack and Class name

:patient Leave the all other to default values

Now type or copy the following


package mypack;

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

@Entity
@Table(name="patient")
public class patient {

private Integer id;
private String firstName;
private String lastName;

@Id
@GeneratedValue
@Column(name="ID")
public Integer getId() {
return id;
}

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

@Column(name="firstname")
public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

@Column(name="lastname")
public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

}



Step 6 : Hibernate Configuration

Now we have the persistent class and its mapping information using Annotations in place.
Let’s configure Hibernate.



Right Click src->New->File. File Name as hibernate.hbm.xml
Paste following code there. Save it as hibernate.cfg.xml. Here you have to give the

username,password and database name according to your MySQL account.


<?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="connection.driver_class">com.mysql.jdbc.Driver</property>
 <property name="connection.url">jdbc:mysql://localhost/sampledb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">123</property>

 <!-- JDBC connection pool (use the built-in) -->
 <property name="connection.pool_size">1</property>

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

  <!-- Enable Hibernate's automatic session context management -->
  <property name="current_session_context_class">thread</property>

  <!-- Disable the second-level cache -->
  <property name="cache.provider_class">org.hibernate.cache.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">update</property>

  <!-- Mapping files -->
  <mapping resource="patient.hbm.xml" />

  </session-factory>
</hibernate-configuration>


Step 7: Create Test class to store the objects

To create new class right click on "mypack" package and select New --> Class and give Name as

Test.java and paste the following code in class file.



package mypack;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.HibernateException;

public class Test {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
createRecords();

}

public static void createRecords() {

try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("**Example : Hibernate 4 SessionFactory**");
System.out.println("----------------------------------------");

Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
patient pt = new patient();
pt.setFirstName("John124");
pt.setLastName("Smith234");
session.saveOrUpdate(pt);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

}


Now right click on test.java file and select Run as -> Java Application
If every thing configured correctly, then you will the see the following lines in the console at the
end

INFO: HHH000126: Indexes: [primary]
Apr 29, 2012 10:14:49 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
**Example : Hibernate 4 SessionFactory**
----------------------------------------
Hibernate: insert into PATIENT (FIRSTNAME, LASTNAME) values (?, ?)

Now go to database and check records are inserted into patient table.

Run again and again to insert more records by changing the last name and first name.
So that in the next step, we can see how we can retrieve the records.


Step 7: Get records and display in the console.

Small Intro on Hibernate Query Language

Hibernate uses a powerful query language (HQL) that is similar in appearance to SQL. Compared with SQL,

however, HQL is fully object-oriented and understands notions like inheritance, polymorphism and

association. Since it is an object-oriented equivalent of SQL, all of the functions of retrieval are

provided out-of-the-box in HQL. These functions can be classified into four categories:

1. Projection

2. Restriction

3. Aggregation

4. Grouping


Examples for Projection
"from patient"

The above will returns all of the instances of the patient.
This is equivalent to the following SQL : SELECT * FROM patient

Examples for Restriction
SELECT * FROM patient WHERE lastname='John';

Coming back to our example, let us get all the patients from the database and print the last name
in the console.

Modified Test.Java as follows

package mypack;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.HibernateException;

public class Test {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
createRecords();
getAllRecords();

}

public static void createRecords() {

try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("**Example : Hibernate 4 SessionFactory**");
System.out.println("----------------------------------------");

Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
patient pt = new patient();
pt.setFirstName("John12");
pt.setLastName("Smith23");
session.saveOrUpdate(pt);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

public static void getAllRecords() {

try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("**Example : Hibernate  SessionFactory**");
System.out.println("----------------------------------------");

List allpatients;

Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q1 = session.createQuery("from patient");
allpatients = q1.list();
for (int i =0; i < allpatients.size(); i++)
{
patient pt = (patient) allpatients.get(i);
System.out.println(pt.getLastName());
}
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

}


Now right click on test.java file and select Run as -> Java Application. Last name will be
printed in the console.


Look and Feel for listitem with paging and with crud actions

Listitem Look and Feel with Pagination and with crud buttons for each record


Output




    Click here to see the demo

    Click here to download the source code






List item with crud buttons


Output ;











ZK ListBox


Let us first design a simple  static list box with crud Buttons as last column.

Hibernate Introduction Part 2


Hibernate Annotations
This example is the same as the first example except that it uses annotations. There we first started
by creating the .hbm.xml file, here there is no need to create it instead we will use annotations to do
the object relational mapping.

Step 1 : Remove the patient.hbm.xml file

Step 2 ; Open the hibernate.cfg.xml and replace the following line

<!-- Mapping files -->
<mapping resource="patient.hbm.xml" />

With


<!-- Mapping Classes -->
<mapping class="mypack.patient" />


Step 3 : Open the patient.java and replace as follows


package mypack;

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



@Entity
@Table(name="patient")
public class patient {

private Integer id;
private String firstName;
private String lastName;

@Id
@GeneratedValue
@Column(name="ID")
public Integer getId() {
return id;
}

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

@Column(name="firstname")
public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

@Column(name="lastname")
public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

}

Step 4:  No Change in Test.java . Just right click as Test.java and run as Java application.

Hibernate POC


I am not sure whether title for this post is correct or wrong. But in the post , i am going to write how hibernate works if we play around in the application.

1. Tables are automatically created
 After Hibernate Introduction Part 1, i just went to the back end database, change the table name from patient
to patient1. Now i again run the application, it runs without any exception. But when i refresh the db at the back end, i saw , again patient table is created and record is inserted.


Hibernate Introduction Part 1


So What is hibernate ?
Here is the answer
Click the following link
Link

:) Well, if you have time, just go thru each and understand. Otherwise, simply put, using hibernate
it is each save the data into the database or load the data from the database.

Well, let's start.

Step 1: Development environment

1. My sql server 5.0  Download
2. Hibernate 4.1.1 Download
3. JDBC Driver for Mysql ((mysql-connector-java-5.1.19.zip)) Download
4. Eclipse IDE

Unzip the hibernate buddle and you should have the following structure after you unzip
Documentation folder
lib Folder
Project folder
log text file
hibernate logo image
license text file


Step 2:

Open mysql and create the following table in any of the exisitng database or create new database.
Here is the script for our table


CREATE TABLE `patient`
(
           `ID` INT(11) NOT NULL AUTO_INCREMENT,
  `FirstName` VARCHAR(100) DEFAULT NULL,
    `LastName` VARCHAR(100) DEFAULT NULL,
           `Email` VARCHAR(200) DEFAULT NULL,
           PRIMARY KEY  (`ID`)
       ) ENGINE=INNODB DEFAULT


Step 3: Eclipse Java project

1. Click File -> New -> Other -> Java Project
2. Say Example1 for Project Name and leave all other to default values.
   (Make sure, JRE has been configured).
3. Next we will add all dependencies in the example1. Now click Example1 project in the project
   explorer and right click -> Click New-> Folder. Say folder name as lib

   Now copy the following files into lib folder
   (Eclipse project explorer accepts all copy and paste operation. For example, you can copy file
    or folder in windows explorer and then you can come back to eclipse project explorer and paste it)

     All the files in Hibernate->Lib->required.
     All the files in Hibernate->Lib->jpa.
     All the files in Hibernate->Lib->envers
     mysql-connector-java-5.1.18-bin.jar


4. Now  setup the build path. In order to execute our example, all the above jar files should be in
class build path

   Again, click on the Example1, right click, and select build Path->configure build path.
   Go to Libraries-> External jars,  browse lib folder you created earlier. Then add external jars by

 selecting all jar files that you copied to lib folder in one of previous step




Step 4: Creating Java beans

Now let us create the java bean for the patient where we want to store in the database.

Again, right click on Example1, Select New -> Class; Package Name : mypack and Class name :patient
Leave the all other to default values

Now type or copy the following

package mypack;

public class patient {

private Integer id;
private String firstName;
private String lastName;

public Integer getId() {
return id;
}

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

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;
}

}


Step 5: Mapping between Java bean and Table.

Let us first summarize what we have done so far. 1) My sql table 2) Java bean.

Now, important step, we will see how to map 1) and 2) , so that whenever new object is created,
it will insert one record in the database.


Hibernate makes persisting the state of your Java objects incredibly simple. However, in order for

Hibernate to know where to story your JavaBeans, or how to map the property of a JavaBean to a database

column, the developer has to provide a bit of direction to the Hibernate framework.

This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table

in the database it has to access, and what columns in that table it should use.


Using JPA annotations also, we can do the same. In this example, first we will see using mapping files
and then we will convert the same example to JPA annotations.


Now let us create the mapping file
Right Click src->New->File. File Name as patient.hbm.xml

Type or copy the below content


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Apr 29, 2012 6:48:24 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="mypack.patient" table="PATIENT">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="firstName" type="java.lang.String">
            <column name="FIRSTNAME" />
        </property>
        <property name="lastName" type="java.lang.String">
            <column name="LASTNAME" />
        </property>
    </class>
</hibernate-mapping>


Step 6 : Hibernate Configuration

Now we have the persistent class and its mapping file in place. Let’s configure Hibernate.

Right Click src->New->File. File Name as hibernate.hbm.xml

Paste following code there. Save it as hibernate.cfg.xml. Here you have to give the username,password

and database name according to your MySQL account.


<?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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/sampledb</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

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

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.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">update</property>

<!-- Mapping files -->
<mapping resource="patient.hbm.xml" />

</session-factory>
</hibernate-configuration>


Step 7: Create Test class to store the objects

To create new class right click on "mypack" package and select New --> Class and give Name as Test.java

and paste the following code in class file.


package mypack;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.HibernateException;

public class Test {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("**Example : Hibernate 4 SessionFactory**");
System.out.println("----------------------------------------");

Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
patient pt = new patient();
pt.setFirstName("John");
pt.setLastName("Smith");
session.saveOrUpdate(pt);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}


Now right click on test.java file and select Run as -> Java Application
If every thing configured correctly, then you will the see the following lines in the console at the
end

INFO: HHH000126: Indexes: [primary]
Apr 29, 2012 10:14:49 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
**Example : Hibernate 4 SessionFactory**
----------------------------------------
Hibernate: insert into PATIENT (FIRSTNAME, LASTNAME) values (?, ?)

Now go to database and check records are inserted into patient table.


Dynamic Include Source


Dynamic Include Source

Let us see how we can dymanically set the source for the include Component

Our objective is if user clicks on male, then load another zul page. If user clicks on female
, then load another page.



Here is the Root Zul File

<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
<window title="Dynamic Include Example" id="rootWin"
apply="mypack.DynamicInclude">
<window id="innerWin">
<radiogroup id="radio">
<radio label="Male" />
<radio label="Female" />
</radiogroup>
</window>
<include id="innerIncld" />
</window>

</zk>

Here is the female.zul

<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
<window title="Female" border="normal">Female zul File</window>
</zk>


Here is the male.zul

<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
<window title="Male" border="normal">Male Zul file</window>
</zk>

Here is the composer

package mypack;

import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Include;
import org.zkoss.zul.Radiogroup;

@SuppressWarnings("rawtypes")
public class DynamicInclude extends GenericForwardComposer {

private static final long serialVersionUID = 1L;
Radiogroup innerWin$radio;
Include innerIncld;

public void onCheck$radio$innerWin() {
boolean tf = innerWin$radio.getSelectedItem().getLabel().equals("Male");
String s = tf ? "male.zul" : "female.zul";
innerIncld.setSrc(s);
}
}

Handle the events in the nested ids space


The following example show how we can handle the events in the nested ids space

Zul File

<window id="win1" title="Win1" border="normal" width="300px" apply="mypack.Example6">
<button id="btn1" label="Win 1 Button" />
<separator bar="true" />
<space />
<window id="win2" title="Win2" border="normal" width="200px">
<button id="btn2" label="Win 2 Button" />
<separator bar="true" />
<space />
<window id="win3" title="Win3 " border="normal" width="200px">
<button id="btn3" label="Win 3 Button" />
</window>
</window>
</window>



In order to manipulate the UI Components, let us follow the MVC Pattern

First we need to create a composer and let us connect the zul and composer by using apply attribute

Here is the composer java class

package mypack;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Textbox;

public class Example6 extends GenericForwardComposer {


public void onClick$btn1(Event event) {
alert("Button 1 Clicked");
}

public void onClick$btn2$win2() {
alert("Button 2 Clicked");
}

public void onClick$btn3$win3$win2() {
alert("Button 3 Clicked");
}

}

ID Space - Different method to access UI Elements


The following example is based on the following zk doc

http://books.zkoss.org/wiki/ZK_Essentials/Introduction_to_ZK/Component_Based_UI
http://books.zkoss.org/wiki/ZK_Developer's_Guide/Fundamental_ZK/Basic_Concepts/UI_Component_Forest
http://books.zkoss.org/wiki/ZK_Developer's_Reference/UI_Composing/ID_Space


Here is the simple zul file

<?page title="Example5" contentType="text/html;charset=UTF-8"?>
<zk>
<window title="Example" id="outerWin" border="normal" apply="mypack.Example5">
<button id="outerBtn" label="Outer Win Button" />
<window id="innerWin" border="normal">
<button id="innerBtn" label="Inner Win Button" />
</window>
</window>
</zk>


Now we will see how we can access all these components and do some actions. In this example,
i have just changed the caption, so that's action for us now.

In order to manipulate the UI Components, let us follow the MVC Pattern

First we need to create a composer and let us connect the zul and composer by using apply attribute

Here is the composer java class

package mypack;

import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Path;

import org.zkoss.zul.Button;
import org.zkoss.zul.Window;

@SuppressWarnings("rawtypes")
public class Example5 extends GenericForwardComposer {

private static final long serialVersionUID = 1L;
private Window outerWin;
private Window innerWin;
private Button innerBtn;
private Button outerBtn;

@SuppressWarnings("unchecked")
public void doAfterCompose(Component comp) throws Exception {
/**
* Dont forget to call super doaftercomposer. By calling this, it will
* add the event listner for us
*/
super.doAfterCompose(comp);

outerWin = (Window) comp;
// Set the outer window title
outerWin.setTitle("Title Changed");

// Now let us try to access outerbtn by different methods

// Using getfellow
outerBtn = (Button) outerWin.getFellow("outerBtn");
outerBtn.setLabel("Outer Button accessed 1");

/**
* The Path provides the utility method getComponent which takes the
* relative path of the component as its argument. outerBtn is
* equivalent to outerWin/outerBtn
*/

// Using Path
outerBtn = (Button) Path.getComponent("/outerWin/outerBtn");
outerBtn.setLabel("Outer Button accessed 2");

/**
* The getFirstChild method returns the first child component of the
* caller. The advantage of using this method is that you don't even
* need to know the component ID to fetch the component.
*/

// Using Getfirstchild
outerBtn = (Button) outerWin.getFirstChild();
outerBtn.setLabel("Outer Button accessed 3");

// Now let us try to access innerBtn by different methods

// Using getfellow
innerBtn = (Button) outerWin.getFellow("innerWin")
.getFellow("innerBtn");
innerBtn.setLabel("inner Button accessed 1");

// Using Path
innerBtn = (Button) Path.getComponent("/outerWin/innerWin/innerBtn");
innerBtn.setLabel("inner Button accessed 2");

// Using Getfirstchild
innerBtn = (Button) outerWin.getFirstChild().getNextSibling()
.getFirstChild();
innerBtn.setLabel("inner Button accessed 3");

// Now let us try to access innerWin by different methods
// Using getfellow

// Using getfellow
innerWin = (Window) outerWin.getFellow("innerWin");
innerWin.setTitle("Inner window accessed 1");

// Using Path
// We can also use (Window)Path.getComponent("outerWin/innerWin");

innerWin =  (Window)Path.getComponent("/outerWin/innerWin");
innerWin.setTitle("Inner window accessed 2");


// Using Getfirstchild
innerWin =  (Window)outerWin.getFirstChild().getNextSibling();
innerWin.setTitle("Inner window accessed 3");
}
}


You can see above, we have used different methods to access the UI Components





Change the color of the selected item in the listbox


Changing Selection Colour - List Box (from default blue) to another custom colour


ZK MVC An Annotation Based Composer For MVC


Finally , we will end using zk 6 An Annotation Based Composer For MVC
This is the 5th post in a series of ZK MVC
Here is the zk documentation and we are following that
and creating new example
http://books.zkoss.org/wiki/Small_Talks/2008/August/ZK_MVC_Made_Easy
http://books.zkoss.org/wiki/Small_Talks/2011/January/Envisage_ZK_6:_An_Annotation_Based_Composer_For_MVC

ZK MVC Using GenericForwardComposer utility class


Welcome back

This is the 4th post in a series of ZK MVC

Here is the zk documentation and we are following that
and creating new example

http://books.zkoss.org/wiki/Small_Talks/2008/August/ZK_MVC_Made_Easy


ZK MVC Using .GenericAutowireComposer utility class


This is the third post in a series of ZK MVC



I am just following the zk documentation and creating another sample 
here is the ZK Documentation url


ZK MVC Using .GenericComposer utility class


This is the second post in a series of ZK MVC




This post is continuation of previous post

ZK Documentation is here
http://books.zkoss.org/wiki/Small_Talks/2008/August/ZK_MVC_Made_Easy

Now we will use Genericcomposer class to reduce some code from my previous post

ZK MVC Using composer interface


This is the first post in a series of ZK MVC

Just going thru the following link to get some idea about MVC
http://books.zkoss.org/wiki/Small_Talks/2008/August/ZK_MVC_Made_Easy

Everything went fine as long as i copied and paste from the examples
But when i started my own example, got into problem and came to know some concepts or tricks or whatever be

Hi
Slowly moving as  a techie guys to come up good product for EMR and PMS

Here is the technology mixture which i have started

ZK 6  + Spring + Hibernate + java ee + Maven + ???????  some more !!! No idea, so far this.

You can see some stupid and simple examples in ZK framework going forward

Have fun