Annotate non persistent properties with the @Transient Annotation

In Most of the cases, all the Java bean properties (example, firstname, lastname, email, etc.) that need to be stored to the database. But in some situation, we might have other properties that do not need to be stored in the database. In this case, we need to say to hibernate that do not take this property for all the Database operation. This can be done using @Transient annotation.

By default, all fields in your class will be persisted to the database if possible. If there is a field that should not be recorded in the database, mark that field with the @Transient annotation

Now let us do an example on the above subject

Step 1:

Create the hibernate setup as shown here;

Step 2:

Now let us modify our patient.java by adding a non persistent field

package mypack;

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

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

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

    @Transient
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @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 3:

Let us modify test.java to create new patient 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;

import Utility.HibernateUtil;

public class Test {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

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

public static void getAllRecords() {
List allpatients;
Session session = HibernateUtil.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());
}
HibernateUtil.CommitTransaction();
}

public static void createpatient() {

Session session = HibernateUtil.beginTransaction();
patient p1 = new patient();
p1.setFirstName("Mark");
p1.setLastName("Anderson");
p1.setPassword("1234");
session.save(p1);
HibernateUtil.CommitTransaction();
}

}


Step 4:


Run the test.java as Java Application and the following is the output


Hibernate: insert into patient (firstname, lastname) values (?, ?)
Hibernate: select patient0_.ID as ID0_, patient0_.firstname as firstname0_, patient0_.lastname as lastname0_ from patient patient0_
John
DAVID
JOSEPH
Anderson


Another good example


public enum Gender { MALE, FEMALE, UNKNOWN }

@Entity
public Person {
private Gender g;
private long id;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long getId() { return id; }
public void setId(long id) { this.id = id; }

public Gender getGender() { return g; }
public void setGender(Gender g) { this.g = g; }

@Transient
public boolean isMale() {
return Gender.MALE.equals(g);
}

@Transient
public boolean isFemale() {
return Gender.FEMALE.equals(g);
}
}

MVVM Example 3–List item

Next we will see how to load the list items using MVVM

Tab box with tool bar CSS

 We will see how we can customize the look and feel for Tabbox With toolbar

Change the location of the label in radio element

 Change the location of the label in radio element

Hibernate 4.1.1 will create the column if we misspelled in the annotation

If we misspelled the column name in the annotation, then hibernate will create that column automatically. I don’t know whether we can turn this feature off.

Steps to Reproduce

  1. Setup the environment as said here.
  2. Now go back to patient.java and change @Column(name="firstname") to @Column(name="firtname")
  3. Now run the test java file.
  4. You can see, it will run successfully without any error.
  5. And now go back to db. and if you check the patient table, now you can see one more column added and null inserted for all the records

MVC–CRUD Application with ZK 5 Data Binding

Here is the summary of what we have completed in this subject.
  1. We created new ZK Project, set up the hibernate and created Modal-View- Controller files to display all the record from the DB. Please click here to go that post.
  2. Next, we added filter feature such that if the user type any value, then the list will be filtered accordingly. Please click here to go that post
  3. Next, we’ve seen how to add more search parameters and filter the list. Please click here to go that post
All these are completed without using any data binding concept. Now let us see how we can use ZK 5 Data binding concepts and makes our job easy. If you are new ZK 5 Data binding, then first go here and learn basic stuffs.

Hibernate–Java Environment setup

Environment

  1. Eclipse 3.7 Indigo IDE Download
  2. Hibernate 4.1.1 Download
  3. JavaSE 1.6  Download
  4. MySQL 5.1 Download
  5. JDBC Driver for MySQL ((MySQL-connector-java-5.1.19.zip)) Download
  6. Extract the Hibernate, MySql driver files in a separate folder

 

Step 1:

  1. 1. In the eclipse, Click New –>  Java Project
  2. Enter the Project Name <ExampleXXXX>
  3. Click Next
  4. Goto Libraries Tab as shown

         image 

Click On Add External Jar files. Add the following files from the hibernate folder and MySQL driver folder.

  • antlr-2.7.7.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.1.Final.jar
  • hibernate-core-4.1.1.Final.jar
  • hibernate-entitymanager-4.1.1.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • javassist-3.15.0-GA.jar
  • jboss-logging-3.1.0.GA.jar
  • jboss-transaction-api_1.1_spec-1.0.0.Final.jar
  • mysql-connector-java-5.1.18-bin.jar

image

Click Finish Button

 

Step 2:

Now let us setup the mysql. Create the following table in mysql

image

Insert some values as shown here

image

Step 3:

Now let us create the Patient Java Bean class with JPA Annotations

 

           image

  1. Right Click on Src folder as shown
  2. Select New->Class
  3. Enter package name as mypack and Class name as patient
  4. Here is the Java Bean code
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:



Create hibernate.cfg.xml




    1. Right Click on Src folder
    2. Select New –> Other->General->File
    3. Enter the file name as hibernate.cfg.xml
    4. Goto the Source view and paste the following code
    5. image


<?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 Classes -->
<mapping class="mypack.patient" />

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


Step 5:



Create Test.java to test all the above are fine.



  1. Right Click on Src->mypack folder
  2. Select New –> Class
  3. Enter the Class Name as Test


image


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) {
getAllRecords();
}

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

}


Step 6:


Right click on Test.Java in the Editor window and Select Run as –> Java Application


The output as follows


**Example : Hibernate  SessionFactory**
----------------------------------------
Hibernate: select patient0_.ID as ID0_, patient0_.firstname as firstname0_, patient0_.lastname as lastname0_ from patient patient0_
John
DAVID
JOSEPH


 


 


Step 7:



Now we will move all the hibernate session creation part into separate class and we will reuse whenever we need it.  We will call this as Hibernate Utility class


package Utility;

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

public class HibernateUtil {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static Configuration getInitConfiguration() {
Configuration config = new Configuration();
config.configure();
return config;
}

public static Session getSession() {
if (factory == null) {
Configuration config = HibernateUtil.getInitConfiguration();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
config.getProperties()).buildServiceRegistry();
factory = config.buildSessionFactory(serviceRegistry);
}
Session hibernateSession = factory.getCurrentSession();
return hibernateSession;
}

public static Session beginTransaction() {
Session hibernateSession;
hibernateSession = HibernateUtil.getSession();
hibernateSession.beginTransaction();
return hibernateSession;
}

public static void CommitTransaction() {
HibernateUtil.getSession().getTransaction().commit();
}

public static void closeSession() {
HibernateUtil.getSession().close();
}

public static void rollbackTransaction() {
HibernateUtil.getSession().getTransaction().rollback();
}

}


 


Step 8:


Now let us reduce the code in test.java as shown


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;

import Utility.HibernateUtil;

public class Test {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

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

public static void getAllRecords() {
List allpatients;
Session session = HibernateUtil.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());
}
HibernateUtil.CommitTransaction();
}

}

How to refer CSS File in ZK Style tag

In this example, we will see how to create CSS file as separate file and include in zul file to change the look and feel

MVVM Examples–Example 2

Concept

Initialization

The binder is responsible for creating and initializing a ViewModel instance. If you want to perform your own initialization in a ViewModel, you can declare your own initial method by annotating a method with @Init . The Binder will invoke this method when initializing a ViewModel. Each ViewModel can only have one initial
method


MVVM Examples–Example 1

Example 1:
In this example, how we can convert MVC GenericForwardComposer into new MVVM + Data binding

Input Form Validation window


We will see here how to validate all the input elements and show all the message in one window after submit button is clicked.  This can be done using ZK Data binding and CreateComponents method.
This example is based on Executions.CreateComponents. For more example, please check here.
Project Structure
image

Step 1:

ValidationMessage.Java
package MyDomain;

public class ValidationMessage 
{
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
}


Step 2:


ValidateWindow.zul

<?xml version="1.0" encoding="UTF-8"?>
<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" arg0="./modalDialog" ?>
<zk>
    <window id="modalDialog" title=" " width="420px" height="auto"
        border="normal" minimizable="false" mode="modal" maximizable="false"
        closable="true" action="hide: slideUp">
        <listbox vflex="1" id="test" model="@{arg.vList}">
            <listhead sizable="true">
                <listheader label="Messages" width="300px" />
            </listhead>
            <!-- define variable p1 here-->
            <listitem self="@{each='p1'}">
                <listcell label="@{p1.Message}" />
            </listitem>
        </listbox>
        <separator />
        <div align="center">
            <button label="Ok" onCreate="self.setFocus(true)"
                onClick="modalDialog.detach()" />
        </div>
    </window>
</zk>




Step 3:


Demo.Zul

<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
    <window id="win" title ="Person" width="420px" height="150px" border="normal"
        minimizable="false" mode="modal" maximizable="false" closable="true"
        apply="MyDomain.DemoComposer" action="show: slideDown;hide: slideUp">

        <grid width="400px">
            <rows>
                <row>
                    First Name:
                    <textbox id="fname"/>
                </row>
                <row>
                    Last Name:
                    <textbox id="lname"/>
                </row>
            </rows>
        </grid>
        <separator />
        <div align="center">
            <button id="Submit" label="Submit" />
        </div>
    </window>
</zk>


Step 4:


DemoComposer.Java

package MyDomain;

import java.util.HashMap;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Textbox;
import java.util.ArrayList;
import java.util.List;

public class DemoComposer extends GenericForwardComposer {

    private Textbox fname;
    private Textbox lname;

    public void onClick$Submit(Event event) {
        if (IsValidInput())
            alert("All are valid. Now you can Save into DB");

    }

    public boolean IsValidInput() {

        List<ValidationMessage> vList = new ArrayList<ValidationMessage>();

        ValidationMessage v1 = new ValidationMessage();

        if (fname.getValue() == "") {
            v1.setMessage("First Name Cannot be Empty");
            vList.add(v1);
        }

        if (lname.getValue() == "") {
            v1 = new ValidationMessage();
            v1.setMessage("Last Name Cannot be Empty");
            vList.add(v1);
        }

        if (vList.size() > 0) 
        {
            final HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("vList", vList);
            Executions.createComponents("ValidateWindow.zul", null, map);
            return false;
        }
        else
            return true;
        
    }

}


Step 5:


Run the demo.zul and without entering any value , click on submit button as shown

image

Download the source as war file

ZK Executions.createComponents

 

Example 1:

Using MVC, we will see how we can call another ZUL File and pass arguments to the ZUL File

image

Step : 1

Demo.Zul file

<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
<window title="new page title" border="normal"
apply="myUI.DemoComposer">
<button id="Create" label="Show Window" onClick="" />
</window>
</zk>


 


Step : 2


DemoComposer.java


package myUI;
import java.util.HashMap;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;

public class DemoComposer extends GenericForwardComposer
{
public void onClick$Create(Event event)
{
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("fname", "senthil");
map.put("lname", "Nathan");
Executions.createComponents("Person.zul",null,map);
}
}


 


Step : 3


<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
<window id="win" width="420px" height="110px"
border="normal" minimizable="false" mode="modal" maximizable="false"
closable="true" action="show: slideDown;hide: slideUp">

<grid width="400px">
<rows>
<row>
First Name:
<textbox value="${arg.fname}" />
</row>
<row>
Last Name:
<textbox value="${arg.lname}" />
</row>
</rows>
</grid>
</window>
</zk>


Step : 4


image

List Item Connected with Hibernate and Search Parameter

 Summary

This example contains one list box with First name and Last Name as search Field. If the user do not give any values for first name and last name, then clicking Go Button will list all the records from the DB.
If the user enters either first name or last name or both, then using like operator, it will retrieve accordingly.

ZK Hibernate Setup

This post will explain how to set up the Hibernate for a ZK Project

Environment

    1. Eclipse 3.7 Indigo IDE Download
    2. Hibernate 4.1.1 Download
    3. JavaSE 1.6 Download
    4. MySQL 5.1 Download
    5. JDBC Driver for MySQL ((MySQL-connector-java-5.1.19.zip)) Download
    6. ZK 6 CE Version
    7. Extract the Hibernate, MySql driver files in a separate folder

Step 1:

 In the Eclipse, Select File –> New –> ZK Project and give Project Name as <AnyNameAsYouWish>
 

Step 2:

Copy the following the following files in <YourProjectName> –> WebContent –> Web-INF –> Lib Folder 

  • antlr-2.7.7.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.1.Final.jar
  • hibernate-core-4.1.1.Final.jar
  • hibernate-entitymanager-4.1.1.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • javassist-3.15.0-GA.jar
  • jboss-logging-3.1.0.GA.jar
  • jboss-transaction-api_1.1_spec-1.0.0.Final.jar
  • mysql-connector-java-5.1.18-bin.jar

                 image

Step 3:

Create Hibernate Configuration File

Expand Java Resources Folder. Right Click on src folder and Select New->General->File and give the name as hibernate.cfg.xml

image

Paste the following code

<?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/drkare</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 Classes -->

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

Please take care to change the DB Name, User and Password according your setup

Step 4:

Now let us create the hibernate utility class where we will establish the DB Configuration using the above configuration file

Right Click on Java Resource folder-> Select New –> Class. Give the Package name as HibernateUtilities and Class name as HibernateUtil.java

image

Paste the following code

package HibernateUtilities;

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

public class HibernateUtil {

    private static SessionFactory factory;
    private static ServiceRegistry serviceRegistry;

    public static Configuration getInitConfiguration() {
        Configuration config = new Configuration();
        config.configure();
        return config;
    }

    public static Session getSession() {
        if (factory == null) {
            Configuration config = HibernateUtil.getInitConfiguration();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(
                    config.getProperties()).buildServiceRegistry();
            factory = config.buildSessionFactory(serviceRegistry);
        }
        Session hibernateSession = factory.getCurrentSession();
        return hibernateSession;
    }

    public static Session beginTransaction() {
        Session hibernateSession;
        hibernateSession = HibernateUtil.getSession();
        hibernateSession.beginTransaction();
        return hibernateSession;
    }

    public static void CommitTransaction() {
        HibernateUtil.getSession().getTransaction().commit();
    }

    public static void closeSession() {
        HibernateUtil.getSession().close();
    }

    public static void rollbackTransaction() {
        HibernateUtil.getSession().getTransaction().rollback();
    }

}

Window Title Change Color

List item Data Binding

 

Now let us see how we can load the items in the list item using Data binding.

Step 1:

Create a Zul Project as follows

image

 

Step 2 :

Create Person POJO Class

image

Java Code

package mydomain;

public class Person {

private String _firstName = "";
private String _lastName = "";

// getter and setters
public void setFirstName(String firstName) {
_firstName = firstName;
}

public String getFirstName() {
return _firstName;
}

public void setLastName(String lastName) {
_lastName = lastName;
}

public String getLastName() {
return _lastName;
}

public void setFullName(String f) {
// do nothing.
}

public String getFullName() {
return _firstName + " " + _lastName;
}

}



 


Step 3 :


Demo.Zul File


<?xml version="1.0" encoding="UTF-8"?>
<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" arg0="./myWin" ?>
<zk>
<window id='myWin' title="MVC example" border="normal"
apply="mydomainUI.DemoComposer">
Example for "for each" using MVC Controller
<listbox model="@{myWin$DemoComposer.persons}">
<listhead sizable="true">
<listheader label="First Name" width="100px" />
<listheader label="Last Name" width="285px" />
</listhead>
<listitem self="@{each=person}">
<listcell label="@{person.firstName}" />
<listcell label="@{person.LastName}" />
</listitem>
</listbox>
</window>
</zk>


 





Step 4:


Composer


package mydomainUI;

import java.util.ArrayList;
import java.util.List;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Textbox;
import mydomain.Person;

public class DemoComposer extends GenericForwardComposer {

private List<Person> persons = new ArrayList<Person>();


public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
Person p1 = new Person();
p1.setFirstName("John");
p1.setLastName("Robert");
persons.add(p1);

p1 = new Person();
p1.setFirstName("Rosy");
p1.setLastName("Sean");
persons.add(p1);

}

public List<Person> getPersons() {
return persons;
}



}

 

Step 5:


Run the ZUL File, The output as follows


image



ZK Data Binding


This is based on ZK 5 Data binding using Data Bind Manager org.zkoss.zkplus.databind.AnnotateDataBinderInit

Data binding is a mechanism that automates the data-copy plumbing code (CRUD) between UI components and the  data source. Application developers only have to tell the data binding manager about the associations between UI components and the data source. Then, the data -binding manager will do all the loading (loading data from the data source to UI components) and saving (saving data from UI component into the data source) jobs automatically
Now, let us start with simple example. You can find more details in ZK 5 Developer Reference Document.
The following example uses MVC Pattern design + ZK 5 Data binding concepts.

Step 1:
Create ZK Project as shown.
image
Step 2:
First of all, we have to define a data source as a data bean. In this example, we use Person class as an example
that holds the information of a person, say, first name, and last name
image
Here is the Code
package mydomain;
 
public class Person {
 
    private String _firstName = "";
    private String _lastName = "";
 
    // getter and setters
    public void setFirstName(String firstName) {
        _firstName = firstName;
    }
 
    public String getFirstName() {
        return _firstName;
    }
 
    public void setLastName(String lastName) {
        _lastName = lastName;
    }
 
    public String getLastName() {
        return _lastName;
    }
 
    public void setFullName(String f) {
        // do nothing.
    }
 
    public String getFullName() {
        return _firstName + " " + _lastName;
    }
 
}

Step 3:



Activates Data Binding Manager

The Data Binding Manager can be activated by defining the page Initializer at the top of every page.
<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" ?>


Demo.zul File


<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit"?>
<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
    <window title="ZK Data Binding" border="normal">
 
        <grid width="400px">
            <rows>
                <row>
                    First Name:
                    <textbox  />
                </row>
                <row>
                    Last Name:
                    <textbox  />
                </row>
                <row>
                    Full Name:
                    <label  />
                </row>
            </rows>
        </grid>
    </window>
</zk>

Step 4:



Associate UI Components with Data Source


After adding the source data and activating the data-binding manager, you have to define the required UI objects and then associate them with the data source. ZUML annotation expression can be used to tell the data-binding manager the relationship between the data source and UI components. Its usage is very straightforward, simply by declaring the annotation into the component's attribute directly.
<component-name attribute-name="@{bean-name.attribute-name}'''"'''/>

Example

<textbox value="@{person.firstName}"


Data binding works with ZK MVC such as that:
1. Controller class provides a getter method to obtain the bean, or Collection.
2. Declare the bean, or Collection, as the value for a UI component in ZUL. The data binder will call the Controller class' getter method to append data to UI.


Modified Demo.Zul File


<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit"?>
<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
    <window id="win" title="ZK Data Binding" border="normal" apply="UI.DemoComposer">
 
        <grid width="400px">
            <rows>
                <row>
                    First Name:
                    <textbox  value="@{win$DemoComposer.person.firstName}"/>
                </row>
                <row>
                    Last Name:
                    <textbox  value="@{win$DemoComposer.person.LastName }"/>
                </row>
                <row>
                    Full Name:
                    <label  />
                </row>
            </rows>
        </grid>
    </window>
</zk>


Modified  DemoComposer.Java


package UI;
 
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Textbox;
 
import mydomain.Person;
 
 
public class DemoComposer extends GenericForwardComposer {
 
    
    Person person = new Person();
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
        //prepare the example person object
        person.setFirstName("George");
        person.setLastName("Bush");
    }
    
    public String getFirstName()
    {
        return person.getFirstName();
                
    }
 
    public String getLastName()
    {
        return person.getLastName();
                
    }
 
}




Please remember the following always
Data binding works with ZK MVC such as that:
1. Controller class provides a getter method to obtain the bean, or Collection.
2. Declare the bean, or Collection, as the value for a UI component in ZUL. The data binder will call the Controller class' getter method to append data to UI.


In the composer, instead of writing getter for each property, we can get return the object of the bean as follows without changing any thing on the zul file as shown below



package UI;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Textbox;
import mydomain.Person;


public class DemoComposer extends GenericForwardComposer {
    Person person = new Person();


    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
        // prepare the example person object
        person.setFirstName("George");
        person.setLastName("Bush");
    }


    /*
     * public String getFirstName() { return person.getFirstName(); } public
     * String getLastName() { return person.getLastName(); }
     */
    public Person getPerson() {
        return this.person;
    }
}