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