Requirement Constraints

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg
Showing posts with label ZK Hibernate. Show all posts
Showing posts with label ZK Hibernate. Show all posts

Monday, 8 April 2013

ZK MVC CRUD With Spring 3 + JPA + Hibernate 4 Entity Manager

Posted on 11:45 by Unknown

A simple CRUD Application based on JPA.

Overview
This article will explain you step by step how to create simple CRUD application using ZK as Presentation layer with Spring 3 and JPA (Hibernate vendor).

What is JPA and why JPA
The Java Persistence API, referred as JPA is a object-relational mapping solution to enterprise Java applications.
JPA is a spec and not an implementation, so if you choose JPA, you still have to pick an implementation. You can pick Hibernate, Top link, and any other ORM that implements JPA.

Using JPA does not tie you to any particular ORM Like hibernate, toplink, etc. EntityManager provides vendor independent access to persistence. Portability across application servers and persistence products (avoids vendor lock-in).

Developers can choose the best ORM implementation according to the application requirement. For example, production can be started from the free versions of ORM implementation and when the needs arise it can be switched to the commercial version of the ORM framework. You can switch the persistence provides without changing the code. So, ORM framework independence is another another big benefit of JPA

Hibernate ORM
In this example, we are going to choose Hibernate as ORM vendor to build the simple CRUD Application.

Spring and Hibernate ORM Framework Integration.
There are lot of articles on the net about this topic. I recommend to the read following articles on this subject.

1. http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/
2. http://static.springsource.org/spring/docs/2.5.x/reference/orm.html
3. http://blog.springsource.org/2012/04/06/migrating-to-spring-3-1-and-hibernate-4-1/
4. http://javaprogrammingtips4u.blogspot.in/2010/04/spring-integration-with-hibernate_23.html

Technologies used in this example:

1. ZK 6.5.1 CE Version.
2. Hibernate-entitymanager 4.1.9 Final
3. Spring-orm 3.2.0 Release
4. Spring-web 3.2.0 Release
5. Java mysql connector 5.1.22

In mysql, create the following table

image
Part 1: First let us setup the development environment. Download this document and follow the step by step instruction to install the necessary software’s.

Part 2: This post explain how to create ZK Maven project in eclipse IDE as step by step.
Part 3: This post explain how to configure database, user name, password, etc using persistence.xml file
Part 4: This post explain how to integrate Spring and Hibernate.
Part 5: This post explain how to create DAO and service layer for the CRUD operation.
Part 6: This post explain how to create Presentation layer using ZK Framework.


Output before with ZK Default CSS Style

image

image

Output after defining our own CSS for each component.

image

image

Video demo:
http://screencast.com/t/DFRiwmpNHq

You can download the source code here

MVVM Version of this tutorial is available here

Read More
Posted in ZK Hibernate, ZK MVC CRUD Examples, ZK Spring | No comments

Tuesday, 7 August 2012

ZK Hibernate one to Many annotation mapping bidirectional CRUD example using MVVM

Posted on 02:02 by Unknown

In this post, we will see how we can implement hibernate one to Many mapping (master & detail) bidirectional using ZK Components

If you new to hibernate, please look the following URL to understand better on one to many mapping in hibernate.
Example1
Example2

Now let us start with ZK.

Step : 1

Let us set up the environment. Follow this post to set up Hibernate with ZK in eclipse IDE.

 

Step : 2

Let us set up the mysql tables as follows.

image_thumb6_thumb[4]


Now let us start creating individual files

Department.java

package domain;


import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.OneToMany;
@Entity
@Table(name = "department")
public class Department implements Cloneable {

@Id
@GeneratedValue
@Column(name = "ID")
private int ID;

@Column(name = "DepartName")
private String departName;


/**
mappedBy – means “I am not the owner side”, I am mapped by Employee from the other side of the relationship.
It will also not create the database column which makes sense, I would expect a foreign key on the Employee table instead.
Here we have used department as mapped by, so there must be property on the Employee Class.

Department has a bidirectional one to many relationship with Employee through the department property.
You don't have to (must not) define any physical mapping in the mappedBy side.

orphanRemoval=true is used because, even though we specified cascadetype all, but if only child records are deleted,
then when you save the master, the child will not delete. for this, we have used orphanRemoval=true.

**/

@OneToMany(fetch=FetchType.EAGER, cascade = CascadeType.ALL, mappedBy="department", orphanRemoval=true)
List<Employees> employees;

public int getID() {
return ID;
}

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

public String getDepartName() {
return departName;
}

public void setDepartName(String departName) {
this.departName = departName;
}

public List<Employees> getEmployees() {
return employees;
}

public void setEmployees(List<Employees> employees) {
this.employees = employees;
}

public Object clone() throws CloneNotSupportedException {
return super.clone();
}


}


Employees.java


package domain;

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


@Entity
@Table(name = "employees")
public class Employees implements Cloneable {

@Id
@GeneratedValue
private int ID;
@Column(name = "firstName")
private String firstName;

@Column(name = "lastName")
private String lastName;

@ManyToOne
@JoinColumn(name="DepartmentID")
private Department department;

public int getID() {
return ID;
}

public void setID(int iD) {
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;
}

public Department getDepartment() {
return department;
}

public void setDepartment(Department department) {
this.department = department;
}

public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}


DepartmentDAO.java


package domainDAO;

import java.util.List;

import domain.Department;

import org.hibernate.Query;
import org.hibernate.Session;

import HibernateUtilities.HibernateUtil;

public class DepartmentDAO {

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

public void saveOrUpdate(Department p1) {

try {
Session session = HibernateUtil.beginTransaction();
session.saveOrUpdate(p1);
HibernateUtil.CommitTransaction();
} catch (RuntimeException e) {
e.printStackTrace();
}

}

public Integer delete(Department p1) {
try {
Session session = HibernateUtil.beginTransaction();
session.delete(p1);
HibernateUtil.CommitTransaction();
return 1;
} catch (RuntimeException e) {
e.printStackTrace();
return 0;
}

}
}


DepartmentCRUDVM.java


package domainVMS;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.ExecutionArgParam;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import bsh.This;

import domain.Department;
import domain.Employees;
import domainDAO.DepartmentDAO;

public class DepartmentCRUDVM {

@Wire("#DepartmentCRUD")
private Window win;

private boolean makeAsReadOnly;
private Department selectedDepartment;
private List<Employees> employees = new ArrayList<Employees>();
private Employees curSelectedEmployee;
private Integer curSelectedEmployeeIndex;
private String recordMode;

public void setEmployees(List<Employees> employees) {
this.employees = employees;
}

public String getRecordMode() {
return recordMode;
}

public void setRecordMode(String recordMode) {
this.recordMode = recordMode;
}

public Integer getCurSelectedEmployeeIndex() {
return curSelectedEmployeeIndex;
}

public void setCurSelectedEmployeeIndex(Integer curSelectedEmployeeIndex) {
this.curSelectedEmployeeIndex = curSelectedEmployeeIndex;
}

public boolean isMakeAsReadOnly() {
return makeAsReadOnly;
}

public void setMakeAsReadOnly(boolean makeAsReadOnly) {
this.makeAsReadOnly = makeAsReadOnly;
}

public Department getSelectedDepartment() {
return selectedDepartment;
}

public void setSelectedDepartment(Department selectedDepartment) {
this.selectedDepartment = selectedDepartment;
}

public List<Employees> getallEmployees() {
return employees;
}

public Employees getCurSelectedEmployee() {
return curSelectedEmployee;
}

public void setCurSelectedEmployee(Employees curSelectedEmployee) {
this.curSelectedEmployee = curSelectedEmployee;
}

@Init
public void initSetup(@ContextParam(ContextType.VIEW) Component view,
@ExecutionArgParam("sDepartment") Department d1,
@ExecutionArgParam("recordMode") String recordMode)
throws CloneNotSupportedException {
Selectors.wireComponents(view, this, false);

setRecordMode(recordMode);
if (recordMode.equals("NEW")) {
this.selectedDepartment = new Department();
}

if (recordMode.equals("EDIT")) {
this.selectedDepartment = (Department) d1.clone();
setEmployees(d1.getEmployees());
}

if (recordMode == "READ") {
setMakeAsReadOnly(true);
win.setTitle(win.getTitle() + " (Readonly)");
}

}

@Command
public void addNewEmployee() {

final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("sEmployee", null);
map.put("recordMode", "NEW");
Executions.createComponents("EmployeeCRUD.zul", null, map);
}

@Command
public void editThisEmployee() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("sEmployee", this.curSelectedEmployee);
setCurSelectedEmployeeIndex(employees.indexOf(curSelectedEmployee));
map.put("recordMode", "EDIT");
Executions.createComponents("EmployeeCRUD.zul", null, map);
}

@SuppressWarnings({ "unchecked", "rawtypes" })
@Command
public void deleteThisEmployee() {

String str = "The \""
+ this.curSelectedEmployee.getLastName()
+ "\" will be permanently deleted and the action cannot be undone.";

Messagebox.show(str, "Confirm", Messagebox.OK | Messagebox.CANCEL,
Messagebox.QUESTION, new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
if (((Integer) event.getData()).intValue() == Messagebox.OK) {
employees.remove(curSelectedEmployee);
BindUtils.postNotifyChange(null, null,
DepartmentCRUDVM.this, "allEmployees");
}
}
});
}

@Command
public void save() {
selectedDepartment.setEmployees(employees);
new DepartmentDAO().saveOrUpdate(selectedDepartment);
Map args = new HashMap();
args.put("pDepartment", this.selectedDepartment);
args.put("recordMode", this.recordMode);
BindUtils.postGlobalCommand(null, null, "updateDepartmentInfo", args);
win.detach();
}

@Command
public void closeThis() {
win.detach();
}

@GlobalCommand
@NotifyChange("allEmployees")
public void updateEmployeeInfo(@BindingParam("pEmployee") Employees e1,
@BindingParam("recordMode") String recordMode) {

if (recordMode.equals("EDIT")) {
e1.setDepartment(selectedDepartment);
employees.set(this.curSelectedEmployeeIndex, e1);
}

if (recordMode.equals("NEW")) {
e1.setDepartment(selectedDepartment);
employees.add(e1);
}
}

}


DepartmentListVM.java


package domainVMS;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Messagebox;
import domain.Department;
import domainDAO.DepartmentDAO;

public class DepartmentListVM {

private List<Department> departments= new ArrayList<Department>();
private Department curSelectedDepartment;
private Integer curSelectedDepartmentIndex;


public Integer getCurSelectedDepartmentIndex() {
return curSelectedDepartmentIndex;
}
public void setCurSelectedDepartmentIndex(Integer curSelectedDepartmentIndex) {
this.curSelectedDepartmentIndex = curSelectedDepartmentIndex;
}
public Department getCurSelectedDepartment() {
return curSelectedDepartment;
}
public void setCurSelectedDepartment(Department curSelectedDepartment) {
this.curSelectedDepartment = curSelectedDepartment;
}

public List<Department> getallDepartments() {
return departments;
}

@Init
public void initSetup() {
departments= new DepartmentDAO().getAllDepartment();
}

@Command
public void addNewDepartment() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("sDepartment", null);
map.put("recordMode", "NEW");
Executions.createComponents("DepartmentCRUD.ZUL", null, map);
}

@Command
public void editThisDepartment()
{
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("sDepartment", this.curSelectedDepartment);
map.put("recordMode", "EDIT");
setCurSelectedDepartmentIndex(departments.indexOf(curSelectedDepartment));
Executions.createComponents("DepartmentCRUD.ZUL", null, map);
}

//The following method will be called from DepartmentCRUDVM.java after the save
@GlobalCommand
@NotifyChange("allDepartments")
public void updateDepartmentInfo(@BindingParam("pDepartment") Department d1,
@BindingParam("recordMode") String recordMode) {

if (recordMode.equals("EDIT")) {
departments.set(this.curSelectedDepartmentIndex, d1);
}

if (recordMode.equals("NEW")) {
departments.add(d1);
}
}


@SuppressWarnings({ "unchecked", "rawtypes" })
@Command
public void deleteThisDepartment()
{
int OkCancel;

String str = "The Selected \"" + curSelectedDepartment.getDepartName()
+ "\" will be deleted.";
OkCancel = Messagebox.show(str, "Confirm", Messagebox.OK
| Messagebox.CANCEL, Messagebox.QUESTION);
if (OkCancel == Messagebox.CANCEL) {
return;
}

str = "The \""
+ curSelectedDepartment.getDepartName()
+ "\" will be permanently deleted and the action cannot be undone.";

Messagebox.show(str, "Confirm", Messagebox.OK | Messagebox.CANCEL,
Messagebox.QUESTION, new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
if (((Integer) event.getData()).intValue() == Messagebox.OK) {
new DepartmentDAO().delete(curSelectedDepartment);
departments.remove(departments.indexOf(curSelectedDepartment));
BindUtils.postNotifyChange(null, null,
DepartmentListVM.this, "allDepartments");
}
}
});
}

}


EmployeeCRUDVM.java


package domainVMS;

import java.util.HashMap;
import java.util.Map;

import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.ExecutionArgParam;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import domain.Employees;

public class EmployeeCRUDVM {

@Wire("#win")
private Window win;

private Employees selectedEmployee;
private Employees selectedEmployeeOrg;

private boolean makeAsReadOnly;
private String recordMode;


public Employees getSelectedEmployeeOrg() {
return selectedEmployeeOrg;
}

public void setSelectedEmployeeOrg(Employees selectedEmployeeOrg) {
this.selectedEmployeeOrg = selectedEmployeeOrg;
}

public String getRecordMode() {
return recordMode;
}

public void setRecordMode(String recordMode) {
this.recordMode = recordMode;
}

public Employees getSelectedEmployee() {
return selectedEmployee;
}

public void setSelectedEmployee(Employees selectedEmployee) {
this.selectedEmployee = selectedEmployee;
}

public boolean isMakeAsReadOnly() {
return makeAsReadOnly;
}
public void setMakeAsReadOnly(boolean makeAsReadOnly) {
this.makeAsReadOnly = makeAsReadOnly;
}

@Init
@NotifyChange("selectedEmployee")
public void initSetup(@ContextParam(ContextType.VIEW) Component view,
@ExecutionArgParam("sEmployee") Employees selectedEmployee,
@ExecutionArgParam("recordMode") String recordMode) throws CloneNotSupportedException {
Selectors.wireComponents(view, this, false);
setRecordMode(recordMode);


if (recordMode.equals("NEW")) {
this.selectedEmployee = new Employees();
}

if (recordMode.equals("EDIT")) {
System.out.println("Value is " + selectedEmployee.getFirstName());
this.selectedEmployeeOrg = selectedEmployee;
this.selectedEmployee= (Employees) selectedEmployee.clone();
}

if (recordMode == "READ") {
setMakeAsReadOnly(true);
win.setTitle(win.getTitle() + " (Readonly)");
}

}

@Command
public void save() {
Map args = new HashMap();
args.put("pEmployee", this.selectedEmployee);
args.put("recordMode", this.recordMode);
BindUtils.postGlobalCommand(null, null, "updateEmployeeInfo", args);
win.detach();
}

@Command
public void closeThis() {
win.detach();
}
}
HibernateUtil.java


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

}



HibernateUtilities.cfg.xml


<?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>



<!-- Mapping Classes -->
<mapping class="domain.Department" />
<mapping class="domain.Employees" />

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


DepartmentCRUD.ZUL


<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
<window title="One to Many Hibernate using MVVM" border="normal"
id="DepartmentCRUD" width="430px" height="520px"
apply="org.zkoss.bind.BindComposer" minimizable="false" mode="modal"
maximizable="false" closable="true"
viewModel="@id('vm') @init('domainVMS.DepartmentCRUDVM')">
<separator />
<label value="Department information" />
<separator />
<panel width="100%">
<panelchildren>
<separator />
<grid width="99.5%">
<columns>
<column label="" width="150px" />
<column label="" />
</columns>
<rows>
<row>
<hbox>
<label value="Department Name" />
<label value="*" />
</hbox>
<textbox name="name"
readonly="@load(vm.makeAsReadOnly)"
value="@bind(vm.selectedDepartment.departName)" cols="20" />
</row>
</rows>
</grid>

<separator />
<separator />
<separator />
<separator />

<label value="Employee information" />
<separator />
<div>
<button label="Add New Employee"
onClick="@command('addNewEmployee')" />
</div>
<separator />
<listbox id="test" model="@load(vm.allEmployees)"
selectedItem="@bind(vm.curSelectedEmployee)">
<listhead sizable="true">
<listheader label="First Name" />
<listheader label="Last Name" />
<listheader label="Action" />
</listhead>
<template name="model" var="p1">
<listitem>
<listcell label="@load(p1.firstName)" />
<listcell label="@load(p1.lastName)" />
<listcell>
<hbox spacing="20px">
<image sclass="fimageDelete"
onClick="@command('deleteThisEmployee')" />
<image sclass="fimageedit"
onClick="@command('editThisEmployee')" />
</hbox>
</listcell>
</listitem>
</template>
</listbox>
</panelchildren>
</panel>
<separator />
<div align="center">
<button id="submit" label="Submit"
onClick="@command('save')" visible="@load(not vm.makeAsReadOnly)" />
<button id="cancel"
label="@load(vm.makeAsReadOnly ?'Ok':'Cancel')"
onClick="@command('closeThis')" />
</div>
</window>
</zk>


DepartmentList.zul


<?page title="DepartmentList" contentType="text/html;charset=UTF-8"?>
<zk>
<style>
.z-listcell.red .z-listcell-cnt, .z-label.red{ color:red; }

/* Start: Action Images- Edit
---------------------------------------------- */

.fimageedit { width: 25px; background-image:
url('./images/icon-edit.png'); background-repeat: no-repeat;
border: 0 none; cursor: pointer; }

/* End: Action Images - Edit
---------------------------------------------- */


/* Start: Action Images- Delete
---------------------------------------------- */

.fimageDelete { width: 25px; background-image:
url('./images/icon-trash-red.png'); background-repeat:
no-repeat; border: 0 none; cursor: pointer; }

/* End: Action Images - Delete
---------------------------------------------- */


/* Start: Action Images- Active
---------------------------------------------- */

.fimageActive { width: 25px; background-image:
url('./images/icon-enable.png'); background-repeat: no-repeat;
border: 0 none; cursor: pointer; }

/* End: Action Images - Active
---------------------------------------------- */

/* Start: Action Images- Inactive' ]

---------------------------------------------- */

.fimageInactive { width: 25px; background-image:
url('./images/icon-disable.png'); background-repeat: no-repeat;
border: 0 none; cursor: pointer; }

/* End: Action Images - InActive
---------------------------------------------- */

.z-listcell.highlightcell .z-listcell-cnt,
.z-label.highlightcell { color:blue; cursor: pointer; }


</style>
<window title="One to Many Hibernate using MVVM" border="normal"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('myvm') @init('domainVMS.DepartmentListVM')">

<div>
<button label="Add New Department"
onClick="@command('addNewDepartment')" />
</div>
<separator />

<listbox id="test" model="@load(myvm.allDepartments)"
selectedItem="@bind(myvm.curSelectedDepartment)">
<listhead sizable="true">
<listheader label="Department Name" width="400px"
sort="auto(departName)" />
<listheader label="Action" />
</listhead>
<template name="model" var="p1">
<listitem>
<listcell label="@load(p1.departName)"
onClick="@command('openAsReadOnly')" sclass="highlightcell" />
<listcell>
<hbox spacing="20px">
<image sclass="fimageDelete" onClick="@command('deleteThisDepartment')" />
<image sclass="fimageedit"
onClick="@command('editThisDepartment')" />
</hbox>
</listcell>
</listitem>
</template>
</listbox>
</window>
</zk>


EmployeeCRUD.zul


<zk>
<window id="win" title="Employee" width="520px" height="220px"
border="normal" minimizable="false" mode="modal" maximizable="false"
closable="true" action="show: slideDown;hide: slideUp"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('domainVMS.EmployeeCRUDVM')">
<separator />
<label value="Employee information" />
<separator />
<panel width="100%">
<panelchildren>
<separator />
<grid width="99.5%">
<columns>
<column label="" width="150px" />
<column label="" />
</columns>
<rows>
<row>
<hbox>
<label value="First Name" />
<label value="*" />
</hbox>
<textbox name="name"
readonly="@load(vm.makeAsReadOnly)"
value="@bind(vm.selectedEmployee.firstName)" cols="50" />
</row>
<row>
<hbox>
<label value="Last Name" />
<label value="*" />
</hbox>
<textbox id="txtlastName"
readonly="@load(vm.makeAsReadOnly)"
value="@bind(vm.selectedEmployee.lastName)" />
</row>
</rows>
</grid>
</panelchildren>
</panel>
<separator />
<div align="center">
<button id="submit" label="Submit"
onClick="@command('save')" visible="@load(not vm.makeAsReadOnly)" />
<button id="cancel"
label="@load(vm.makeAsReadOnly ?'Ok':'Cancel')"
onClick="@command('closeThis')" />
</div>
</window>
</zk>




Project Structure

image


 


You can run the departmentlist.zul file and check the output.


 


image


 


You can download the source code here.


You can also download as individual files here.



  1. Department.java
  2. DepartmentCRUD.ZUL
  3. DepartmentCRUDVM.java
  4. DepartmentDAO.java
  5. DepartmentList.zul
  6. DepartmentListVM.java
  7. EmployeeCRUD.zul
  8. EmployeeCRUDVM.java
  9. Employees.java
  10. HibernateUtil.java
  11. icon-edit.png
  12. icon-enable.png
  13. icon-trash-red.png
Read More
Posted in ZK Hibernate | No comments

Friday, 6 July 2012

ZK Hibernate one to one annotation mapping bidirectional CRUD example using MVVM

Posted on 10:36 by Unknown

In this post, we will see how we can implement hibernate one to one mapping bidirectional using ZK Components

In bi-directional mapping, the parent table can be retrieved by the child table and the child table can be retrieved by the parent table. Means retrieval can be done in both direction or bi-directional. In this example, we have two tables caller persona and users. We will create CRUD operation for users which also takes care of inserting record in the person tabke.

ZK Version 6
Project Name : HibernateOneToOneMap
Project Structure

image

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

Mysql

image

CREATE  TABLE IF NOT EXISTS `sampledb`.`person` (
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT ,
  `FirstName` VARCHAR(100) NULL DEFAULT NULL ,
  `LastName` VARCHAR(100) NULL DEFAULT NULL ,
  `Email` VARCHAR(100) NULL DEFAULT NULL ,
  PRIMARY KEY (`ID`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1

CREATE  TABLE IF NOT EXISTS `sampledb`.`userlogin` (
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT ,
  `LoginID` VARCHAR(100) NULL DEFAULT NULL ,
  `Password` VARCHAR(100) NULL DEFAULT NULL ,
  `PersonID` BIGINT(20) NULL DEFAULT NULL ,
  PRIMARY KEY (`ID`) ,
  INDEX `FK_userlogin` (`PersonID` ASC) ,
  CONSTRAINT `FK_userlogin`
    FOREIGN KEY (`PersonID` )
    REFERENCES `sampledb`.`person` (`ID` ))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1

person.java

package domain;

import javax.persistence.Column;
import javax.persistence.OneToOne;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;


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

@Id
@GeneratedValue
private int ID;

@Column(name = "FirstName")
private String FirstName;

@Column(name = "LastName")
private String LastName;

@Column(name = "Email")
private String Email;

@OneToOne(mappedBy = "person")
@Cascade(CascadeType.ALL)
private userlogin userlogin;


public userlogin getUserlogin() {
return userlogin;
}

public void setUserlogin(userlogin userlogin) {
this.userlogin = userlogin;
}

public int getID() {
return ID;
}

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

public String getFirstName() {
return FirstName;
}

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

public String getLastName() {
return LastName;
}

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

public String getEmail() {
return Email;
}

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

}

userlogin.java


package domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity
@Table(name = "userlogin")
public class userlogin implements Serializable, Cloneable {

@Id
@GeneratedValue
private int ID;

@Column(name = "LoginID")
private String LoginID;

@Column(name = "Password")
private String Password;


@OneToOne(targetEntity = person.class)
@Cascade(CascadeType.ALL)
@JoinColumn(name = "personid")
private person person;


public person getPerson() {
return person;
}

public void setPerson(person person) {
this.person = person;
}

public int getID() {
return ID;
}

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

public String getLoginID() {
return LoginID;
}

public void setLoginID(String loginID) {
LoginID = loginID;
}

public String getPassword() {
return Password;
}

public void setPassword(String password) {
Password = password;
}




public Object clone() throws CloneNotSupportedException {
/*
* Employee copyObj = new Employee();
* copyObj.setDesignation(this.designation); copyObj.setName(this.name);
* return copyObj;
*/
return super.clone();
}

}

HibernateUtil.java

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

}

 

hibernate.cfg.xml



<?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="domain.person" />
<mapping class="domain.userlogin" />

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



UserCRUDVM.java


package domainVM;

import java.util.HashMap;
import java.util.Map;

import domain.person;
import domain.userlogin;

import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.ExecutionArgParam;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Window;

import DAO.userDAO;

public class UserCRUDVM {

private userlogin selectedItem;
private userlogin selectedItemOrg;
private boolean makeAsReadOnly;

@Wire("#win")
private Window win;

public boolean isMakeAsReadOnly() {
return makeAsReadOnly;
}

public void setMakeAsReadOnly(boolean makeAsReadOnly) {
this.makeAsReadOnly = makeAsReadOnly;
}


public userlogin getSelectedItem() {
return selectedItem;
}

public void setSelectedItem(userlogin s1) {
this.selectedItem = s1;
}

@Init
@NotifyChange("selectedItem")
public void initSetup(@ContextParam(ContextType.VIEW) Component view,
@ExecutionArgParam("selectedItem") userlogin s1,
@ExecutionArgParam("recordMode") String recordMode)
throws CloneNotSupportedException {
Selectors.wireComponents(view, this, false);


if (recordMode == "NEW") {
this.selectedItem = new userlogin();
this.selectedItemOrg = new userlogin();
this.selectedItem.setPerson(new person());
}

if (recordMode == "EDIT") {
this.selectedItemOrg = s1;
this.selectedItem = (userlogin) s1.clone();
}

if (recordMode == "READ") {
this.selectedItemOrg = s1;
this.selectedItem = (userlogin) s1.clone();
setMakeAsReadOnly(true);
win.setTitle(win.getTitle() + " (Readonly)");
}

}

@Command
public void save() {

// userlogin u1 = new userlogin();
// u1.setLoginID("sen4");
// u1.setPassword("sen4");
//
// person p1 = new person();
// p1.setEmail("senth4il@mail.com");
// p1.setFirstName("sen4thil");
// p1.setLastName("muth4iah");
// u1.setPerson(p1);
new userDAO().saveOrUpdate(this.selectedItem );
Map args = new HashMap();
args.put("newadded", this.selectedItem);
BindUtils.postGlobalCommand(null, null, "refreshList", args);
win.detach();
}
@Command
public void closeThis() {
win.detach();
}
}

userVM.java

package domainVM;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import DAO.userDAO;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Executions;

import domain.userlogin;

public class userVM {

private List<userlogin> users = null;
private userlogin selectedItem;

public userlogin getSelectedItem() {
return selectedItem;
}

public void setSelectedItem(userlogin selectedItem) {
this.selectedItem = selectedItem;
}

public List<userlogin> getallUsers() {
if (users == null) {
users = new ArrayList<userlogin>();
users = new userDAO().getAllUsersFromDB();
}
return users;
}

@Command
public void addNewUser() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("selectedItem", null);
map.put("recordMode", "NEW");
Executions.createComponents("AddUser.zul", null, map);
}

@Command
@NotifyChange("selectedItem")
public void editThisUser() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("recordMode", "EDIT");
map.put("selectedItem", this.selectedItem);
Executions.createComponents("AddUser.zul", null, map);
}

@Command
public void openAsReadOnly() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("recordMode", "READ");
map.put("selectedItem", this.selectedItem);
Executions.createComponents("AddUser.zul", null, map);
}

@GlobalCommand
@NotifyChange("allUsers")
public void refreshList(@BindingParam("newadded") userlogin p1) {
users = null;
}
}







demo.zul

<?page title="Listitem MVVM Demo with Hibernate" contentType="text/html;charset=UTF-8"?>
<zk>

<style>

/* Start: Action Images- Edit
---------------------------------------------- */

.fimageedit { width: 25px; background-image:
url('./images/icon-edit.png'); background-repeat: no-repeat;
border: 0 none; cursor: pointer; }

/* End: Action Images - Edit
---------------------------------------------- */


/* Start: Action Images- Delete
---------------------------------------------- */

.fimageDelete { width: 25px; background-image:
url('./images/icon-trash-red.png'); background-repeat:
no-repeat; border: 0 none; cursor: pointer; }

/* End: Action Images - Delete
---------------------------------------------- */
.z-listcell.highlightcell .z-listcell-cnt,
.z-label.highlightcell { color:blue; cursor: pointer; }


</style>

<window title="Hibernate one to one Mapping bidirectional "
border="normal" apply="org.zkoss.bind.BindComposer"
viewModel="@id('myvm') @init('domainVM.userVM')">
<div>
<button label="Add User" onClick="@command('addNewUser')" />
</div>
<separator />

<listbox id="test" selectedItem="@bind(myvm.selectedItem)"
model="@load(myvm.allUsers)">
<listhead sizable="true">
<listheader label="Login ID" width="200px" />
<listheader label="Password" width="200px" />
<listheader label="First Name" width="200px" />
<listheader label="Last Name" width="285px" />
<listheader label="email" width="285px" />
<listheader label="Action" />
</listhead>
<template name="model" var="p1">
<listitem>
<listcell label="@load(p1.loginID)" />
<listcell label="@load(p1.password)" />
<listcell label="@load(p1.person.firstName)" />
<listcell label="@load(p1.person.lastName)" />
<listcell label="@load(p1.person.email)" />
<listcell>
<hbox spacing="20px">
<image sclass="fimageDelete" />
<image sclass="fimageedit"
onClick="@command('editThisUser')" />
</hbox>
</listcell>
</listitem>
</template>
</listbox>
</window>
</zk>


AddUser.zul

<zk>
<window id="win" title="User" width="520px" height="280px"
border="normal" minimizable="false" mode="modal" maximizable="false"
closable="true" action="show: slideDown;hide: slideUp"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('domainVM.UserCRUDVM')">
<separator />
<label value="User information" />
<separator />
<panel width="100%">
<panelchildren>
<separator />
<grid width="99.5%">
<columns>
<column label="" width="150px" />
<column label="" />
</columns>
<rows>
<row>
<hbox>
<label value="Login" />
<label value="*" />
</hbox>
<textbox name="Login ID" cols="50"
value="@bind(vm.selectedItem.loginID)" />
</row>
<row>
<hbox>
<label value="Password" />
<label value="*" />
</hbox>
<textbox name="Password" cols="50"
value="@bind(vm.selectedItem.password)" />
</row>

<row>
<hbox>
<label value="First Name" />
<label value="*" />
</hbox>
<textbox name="firstName" cols="50"
value="@bind(vm.selectedItem.person.firstName)" />
</row>
<row>
<hbox>
<label value="Last Name" />
<label value="*" />
</hbox>
<textbox name="firstName" cols="50"
value="@bind(vm.selectedItem.person.lastName)" />
</row>
<row>
<hbox>
<label value="email" />
<label value="*" />
</hbox>
<textbox name="email" cols="50"
value="@bind(vm.selectedItem.person.email)" />
</row>
</rows>
</grid>
</panelchildren>
</panel>
<separator />
<div align="center">
<button id="submit" label="Submit"
onClick="@command('save')" />
<button id="cancel" label="Cancel"
onClick="@command('closeThis')" />
</div>
</window>
</zk>



Now you can run demo.zul and add/edit the users

You can download source here


 

Read More
Posted in ZK Hibernate | No comments
Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • Understanding EDI Structure
    EDI Structure Primary Levels are 1. Interchange Envelops 2. Functional Group 3. Transaction set Data Element A data element is equival...
  • Types of Reimbursement
    Fee-For-Service Fee-for-service is a method of payment where the provider is paid a fee for each procedure performed and billed.Most payer ...
  • EDI 270–5010 Documentation - ISA – Interchange Control Header
    ISA – Interchange Control Header ISA – Interchange Control Header   The ISA is a fixed record length segment and all positions within ea...
  • EDI Instructions
    HIPAA Compliant Codes All the Health care EDI Transaction set should use only the following HIPAA Compliant Codes Physicians Current Pro...
  • ZK ListBox
    Let us first design a simple  static list box with crud Buttons as last column. Here is the code <?page title="Practice List" c...
  • ZK Example for inline Editing with Add New and Delete
    I am quite impressed on this demo from ZK . But adding new record and delete existing record is missing as part of typical CRUD. So i thoug...
  • Java Static Import
    This is one of feature in Java 5. In order to access static members, it is necessary to qualify references with the class they came from. ...
  • ZK MVVM Form Binding CRUD with Spring and Hibernate - Part 4
    Presentation Layer using ZK Framework          In part 3 , We have completed Spring integration with hibernate. In this post, we will des...
  • Hibernate–Java Environment setup
    Environment Eclipse 3.7 Indigo IDE Download Hibernate 4.1.1 Download JavaSE 1.6  Download MySQL 5.1 Download JDBC Driver for MyS...
  • ZK MVVM CRUD With Spring 3 + JPA + Hibernate 4 Entity Manager–Part 3
    Define the persistence.xml file In the Part 2 article , we have seen how to create ZK Maven project and update the default POM.XML with a...

Categories

  • Billing Process
  • C Workbook
  • C++ Workbook
  • Eclipse Tips
  • EDI 5010
  • EMR Appointment Features
  • EMR Labs Stuff
  • EMR PMS Links
  • EMR Use cases
  • EMR Vital Sign
  • Good Website Design
  • Hibernate Criteria Queries
  • Hibernate Introduction
  • Hibernate Introduction Setup
  • Hibernate Mapping
  • Hibernate POC
  • Hibernate Validator
  • Hibernate–Java Environment setup
  • HPI
  • Java
  • Maven
  • MU Certification
  • NPI
  • PQRS
  • Practice Management System
  • Spring Security
  • Tech Links
  • Today Tech Stuff
  • zk
  • ZK Hibernate
  • ZK 5 Databinding
  • ZK Application
  • ZK Calling Another ZUL
  • ZK CheckBox
  • ZK CreateComponents
  • ZK CSS
  • ZK extended Components
  • ZK Foreach
  • ZK Forum Posts
  • ZK Framework
  • ZK Hibernate Setup
  • ZK ID Space
  • ZK Include
  • ZK Installation
  • ZK iReport
  • ZK Layout
  • ZK Listitem Pagination
  • ZK Message Box
  • ZK MVC
  • ZK MVC Combox Box
  • ZK MVC CRUD Examples
  • ZK MVC Listbox
  • ZK MVVM
  • ZK MVVM Combo
  • ZK MVVM CRUD
  • ZK MVVM ListBox
  • ZK Spring
  • ZK TextBox

Blog Archive

  • ▼  2013 (105)
    • ▼  December (3)
      • EDI Instructions
      • Understanding EDI Structure
      • What is an EDI ?
    • ►  September (7)
    • ►  August (13)
    • ►  July (1)
    • ►  June (11)
    • ►  May (3)
    • ►  April (14)
    • ►  March (19)
    • ►  February (21)
    • ►  January (13)
  • ►  2012 (177)
    • ►  December (1)
    • ►  November (13)
    • ►  October (19)
    • ►  September (24)
    • ►  August (26)
    • ►  July (6)
    • ►  June (37)
    • ►  May (30)
    • ►  April (16)
    • ►  March (1)
    • ►  January (4)
  • ►  2011 (5)
    • ►  December (1)
    • ►  November (1)
    • ►  July (1)
    • ►  June (1)
    • ►  April (1)
  • ►  2010 (1)
    • ►  September (1)
Powered by Blogger.

About Me

Unknown
View my complete profile