MVVM–List Item–Hibernate–MySQL–Part 1

In every application, we will always have the listing page where we can list the records from the DB, from there another model window will be used to Add/Edit records.

In this post, we will see how we can do the following stuffs

1. Bind the List Item Using New zk 6 Data binding  with MVVM Pattern
2. Retrieve the values from the DB – Mysql using Hibernate as ORM Tool.
3. How to change the color of the particular row based on some condition.
4. How to handle double click event on the List item.
5. How to sort the values in the List Item.

ZK Version : ZK 6

Project Name :ListItemMVVMHibernate

Step 1:  ZK + Hibernate Setup
Please follow this post to setup the Project and related jar files needed for this example

Here is the project structure after the Step : 1

 image

Step :  2

Now let us create our MySQL table as follows

CREATE TABLE `person` (
`ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
`FirstName` VARCHAR(100) DEFAULT NULL,
`LastName` VARCHAR(100) DEFAULT NULL,
`Email` VARCHAR(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=INNODB DEFAULT CHARSET=latin1


Step : 3


Now let us write Java POJO Hibernate annotation class for the above table.


package mydomain;

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

@Entity
@Table(name = "person")
public class Person {

private int ID;
private String FirstName;
private String LastName;
private String Email;

@Id
@GeneratedValue
public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

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

public void setFirstName(String firstName) {
FirstName = firstName;
}

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

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

@Column(name = "Email")
public String getEmail() {
return Email;
}

public void setEmail(String email) {
Email = email;
}

@Override
public String toString() {
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
result.append(this.getClass().getName() + " Object {" + NEW_LINE);
result.append(" User ID : " + this.ID + NEW_LINE);
result.append(" Last Name : " + this.LastName + NEW_LINE);
result.append(" First Name : " + this.FirstName + NEW_LINE);
result.append(" Email : " + this.Email + NEW_LINE);
result.append("}");
return result.toString();
}
}


 



Step : 4


Now let us add the above class in our hibernate.cfg.xml file as folllows


<?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="mydomain.Person" />

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


Step : 4



Now let us create PersonDAO.Java as follows


package domainDAO;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Query;
import org.zkoss.zul.Messagebox;

import HibernateUtilities.HibernateUtil;
import mydomain.Person;

public class PersonDAO {

@SuppressWarnings("unchecked")
public List<Person> getAllPersons() {
List<Person> allrecords = null;
try {
Session session = HibernateUtil.beginTransaction();
Query q1 = session.createQuery("from Person");
allrecords = q1.list();
HibernateUtil.CommitTransaction();
} catch (RuntimeException e) {
e.printStackTrace();
}
return allrecords;
}
}


 


Step : 5
Now let us create our zul file as follows


<?page title="Listitem MVVM Demo with Hibernate" contentType="text/html;charset=UTF-8"?>
<zk>
<style>
.z-listcell.red .z-listcell-cnt, .z-label.red{ color:red; }
</style>
<window title="Listitem MVVM Demo with Hibernate" border="normal"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('myvm') @init('domainVMS.PersonVM')">
<listbox id="test" model="@load(myvm.allPersons)"
selectedItem="@bind(myvm.curSelectedPerson)">
<listhead sizable="true">
<listheader label="First Name" width="400px"
sort="auto(firstName)" />
<listheader label="Last Name" width="285px"
sort="auto(lastName)" />
<listheader label="email" width="285px"
sort="auto(email)" />
</listhead>
<template name="model" var="p1">
<listitem onDoubleClick="@command('onDoubleClicked')">
<listcell label="@load(p1.firstName)" sclass="@load(empty p1.email ?'red':'')"/>
<listcell label="@load(p1.lastName)" sclass="@load(empty p1.email ?'red':'')"/>
<listcell label="@load(p1.email)" />
</listitem>
</template>
</listbox>
</window>
</zk>




Step : 6


Now let us create our VM


package domainVMS;

import java.util.ArrayList;
import java.util.List;
import mydomain.Person;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zul.Messagebox;
import domainDAO.PersonDAO;

public class PersonVM {

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

public Person getCurSelectedPerson() {
return curSelectedPerson;
}

public void setCurSelectedPerson(Person curSelectedPerson) {
this.curSelectedPerson = curSelectedPerson;
}

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

@Init
public void initSetup()
{
persons = new PersonDAO().getAllPersons();

}
@Command
public void onDoubleClicked() {
Messagebox.show(curSelectedPerson.toString());
}
}


Final Project Structure


image


Output


image

If the email is empty, then we are showing that row in different color.



Download the source as war file
In this part 2, we will see how to add/edit person and update into DB