Requirement Constraints

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Thursday, 28 February 2013

ZK MVVM CRUD With Spring 3 + JPA + Hibernate 4 Entity Manager–Part 6

Posted on 10:18 by Unknown

ZK UI Presentation layer.

In the Part 5 article, we have completed our DAO and service layer to do CRUD Operation. In this post, we will design our UI using ZK Framework.

Step 1:
Now let us design the Listing Page which will show all the records from the DB. And also, we will have one Add New button to add new record and for each record, we will have “EDIT”, “View” and “Delete” button as shown here.
image

Select the webapp folder, right click, select new-> folder and enter the folder name as pages as shown

image

Now select the Pages folder, right click, Select New –> Other-> Zul as shown

image

Enter the zul file name as AddressList.zul as shown

image
Copy the following code to list the records from the DB

<?page title="Address List" contentType="text/html;charset=UTF-8"?>
<zk>
<window id="addressList" title="Address List" border="none"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('zkoss.vm.AddressListVM')">
<separator />
<button label="New Address" onClick="@command('onAddNew')"></button>
<separator />
<listbox id="" mold="paging" pageSize="11" pagingPosition="top"
selectedItem="@bind(vm.selectedItem)" model="@load(vm.dataSet)">
<listhead sizable="true">
<listheader label="Full Name" sortDirection="ascending"
sort="auto(fullName)" />
<listheader label="Email" sort="auto(email)" />
<listheader label="Mobile" sort="auto(mobile)" />
<listheader label="Action" />
</listhead>
<template name="model" var="p1">
<listitem>
<listcell label="@load(p1.fullName)" />
<listcell label="@load(p1.email)" />
<listcell label="@load(p1.mobile)" />
<listcell>
<hbox spacing="20px">
<button label="Edit"
onClick="@command('onEdit',addressRecord=p1)">
</button>
<button label="View"
onClick="@command('openAsReadOnly',addressRecord=p1)">
</button>
<button label="Delete"
onClick="@command('onDelete',addressRecord=p1)">
</button>
</hbox>
</listcell>
</listitem>
</template>
</listbox>
</window>
</zk>

1. We are using  MVVM as design pattern.
2. And also, to display the values, we are using MVVM Data binding concept.
3. For event handling, we are using MVVM Command Binding.
4. We are using ZK List box to show the record from the DB.
5. We will display the records using MVVM View Modal


As you see in the following statement


apply="org.zkoss.bind.BindComposer"
        viewModel="@id('vm') @init('zkoss.vm.AddressListVM')">


We need to create View Model in the name of AddressListVM (java class)


Select “java” folder, create a new package called “zkoss.vm” and create a called AddressListVM as shown


image
Here is the code for AddressListVM.Java


package zkoss.vm;

import java.util.HashMap;
import java.util.List;

import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.AfterCompose;
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.GlobalCommand;
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.WireVariable;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Messagebox;

import addressbook.domain.AddressBook;
import addressbook.service.CRUDService;

public class AddressListVM {

@WireVariable
private CRUDService CRUDService;

private AddressBook selectedItem;
private List<AddressBook> allReordsInDB = null;
private Integer selectedItemIndex;

public AddressBook getSelectedItem() {
return selectedItem;
}

/*This method will be called when user select a record in the list*/
public void setSelectedItem(AddressBook selectedItem) {
this.selectedItem = selectedItem;
}

public Integer getSelectedItemIndex() {
return selectedItemIndex;
}

public void setSelectedItemIndex(Integer selectedItemIndex) {
this.selectedItemIndex = selectedItemIndex;
}

/*Only one @AfterCompose-annotated method is allowed at the most in a ViewModel class*/
/* Marker annotation to identify a life-cycle method in View Model.
this method will be called after host component composition has been done (AfterCompose).
*/
@AfterCompose
public void initSetup(@ContextParam(ContextType.VIEW) Component view) {
Selectors.wireComponents(view, this, false);
CRUDService = (CRUDService) SpringUtil.getBean("CRUDService");
allReordsInDB = CRUDService.getAll(AddressBook.class);
}

/* Using this method, the list box will be populated with records
Please note that, we have already initialized this list in the aftercompose.
Whenever, the list of the records has changed, then we will annotate with @NotifyChange("dataSet"), so that,
again this will be called to update the UI
*/
public List<AddressBook> getDataSet() {
return allReordsInDB;
}

/*This method will be called when user press the new button in the Listing screen*/
@Command
public void onAddNew() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("selectedRecord", null);
map.put("recordMode", "NEW");
Executions.createComponents("AddressCRUD.zul", null, map);
}

@Command
public void onEdit(@BindingParam("addressRecord") AddressBook addressBook) {
final HashMap<String, Object> map = new HashMap<String, Object>();
this.selectedItem = addressBook;
map.put("selectedRecord", addressBook);
map.put("recordMode", "EDIT");
setSelectedItemIndex(allReordsInDB.indexOf(selectedItem));
Executions.createComponents("AddressCRUD.zul", null, map);
}

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

@SuppressWarnings({ "rawtypes", "unchecked" })
@Command
public void onDelete(@BindingParam("addressRecord") AddressBook addressBook) {
int OkCancel;
this.selectedItem = addressBook;
String str = "The Selected \"" + addressBook.getFullName()
+ "\" will be deleted.";
OkCancel = Messagebox.show(str, "Confirm", Messagebox.OK
| Messagebox.CANCEL, Messagebox.QUESTION);
if (OkCancel == Messagebox.CANCEL) {
return;
}

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

Messagebox.show(str, "Confirm", Messagebox.OK | Messagebox.CANCEL,
Messagebox.QUESTION, new EventListener() {
public void onEvent(Event event) throws Exception {
if (((Integer) event.getData()).intValue() == Messagebox.OK) {

CRUDService.delete(selectedItem);
allReordsInDB.remove(allReordsInDB
.indexOf(selectedItem));
BindUtils.postNotifyChange(null, null,
AddressListVM.this, "dataSet");

}
}
});
}

// note this will be executed from AddressListCRUDVM.java

@GlobalCommand
@NotifyChange("dataSet")
public void refreshList(
@BindingParam("selectedRecord") AddressBook addressbook,
@BindingParam("recordMode") String recordMode) {
if (recordMode.equals("NEW")) {
allReordsInDB.add(addressbook);
}

if (recordMode.equals("EDIT")) {
allReordsInDB.set(this.selectedItemIndex, addressbook);
}
}

}

Next step, we will create our CRUD form where user can add/edit/view the existing record. As you can see in the addresslistvm.java, we have been calling a zul file name called “AddressCRUD.zul” using ZK Create component utility.


Step 2:
In the same pages folder, create another zul file named as “AddressCRUD.Zul”


image
image



<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
<window title="Address" id="addressCRUD" border="normal" width="30%"
mode="modal" maximizable="false" closable="true"
position="center,parent" apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('zkoss.vm.AddressListCRUDVM')">
<panel width="100%">
<panelchildren>
<separator />
<grid>
<columns>
<column></column>
<column></column>
</columns>
<rows>
<row>
<cell colspan="2">
<vlayout>
<label value="Full Name" />
<textbox id="fullName" hflex="1"
readonly="@load(vm.makeAsReadOnly)"
value="@load(vm.selectedRecord.fullName) @save(vm.selectedRecord.fullName, before='saveThis')"
mold="rounded" />
</vlayout>
</cell>
</row>
<row>
<cell colspan="2">
<vlayout>
<label value="Address" />
<textbox id="address1" hflex="1"
readonly="@load(vm.makeAsReadOnly)"
value="@load(vm.selectedRecord.address1) @save(vm.selectedRecord.address2, before='saveThis')"
mold="rounded" />
</vlayout>
</cell>
</row>
<row>
<cell colspan="2">
<vlayout>
<textbox id="address2" hflex="1"
readonly="@load(vm.makeAsReadOnly)"
value="@load(vm.selectedRecord.address2) @save(vm.selectedRecord.address2, before='saveThis')"
mold="rounded" />
</vlayout>
</cell>
</row>
<row>
<vlayout>
<label value="City" />
<textbox id="City" hflex="1"
readonly="@load(vm.makeAsReadOnly)"
value="@load(vm.selectedRecord.city) @save(vm.selectedRecord.city, before='saveThis')"
mold="rounded" />
</vlayout>
<vlayout>
<grid sclass="vgrid">
<columns>
<column width="30%"></column>
<column></column>
</columns>
<rows>
<row>
<vlayout>
<label value="State" />
<textbox id="State"
readonly="@load(vm.makeAsReadOnly)"
value="@load(vm.selectedRecord.state) @save(vm.selectedRecord.state, before='saveThis')"
hflex="1" mold="rounded" />
</vlayout>
<vlayout>
<label value="ZipCode" />
<textbox id="zipcode"
readonly="@load(vm.makeAsReadOnly)"
value="@load(vm.selectedRecord.zipCode) @save(vm.selectedRecord.zipCode, before='saveThis')"
hflex="1" mold="rounded" />
</vlayout>
</row>
</rows>
</grid>
</vlayout>
</row>
<row>
<cell colspan="2">
<vlayout>
<label value="Email" />
<textbox id="email" hflex="1"
readonly="@load(vm.makeAsReadOnly)"
value="@load(vm.selectedRecord.email) @save(vm.selectedRecord.email, before='saveThis')"
mold="rounded" />
</vlayout>
</cell>
</row>
<row>
<vlayout>
<label value="Mobile" />
<textbox id="Mobile" hflex="1"
readonly="@load(vm.makeAsReadOnly)"
value="@load(vm.selectedRecord.mobile) @save(vm.selectedRecord.mobile, before='saveThis')"
mold="rounded" />
</vlayout>
</row>

</rows>
</grid>
</panelchildren>
</panel>
<separator />
<separator />
<separator />
<div align="center">
<button label="Save" visible="@load(not vm.makeAsReadOnly)"
onClick="@command('saveThis')" mold="trendy" />
<button label="@load(vm.makeAsReadOnly ?'Ok':'Cancel')"
onClick="@command('closeThis')" mold="trendy" />
</div>
<separator />
</window>
</zk>


Next we will create our VM Java class to support the above UI. In the zkoss.vm package, create a class named “AddressListCRUDVM.java”


package zkoss.vm;

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

import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.AfterCompose;
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.zk.ui.Component;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Window;

import addressbook.domain.AddressBook;
import addressbook.service.CRUDService;


public class AddressListCRUDVM {

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

@WireVariable
private CRUDService CRUDService;

private AddressBook selectedRecord;
private String recordMode;
private boolean makeAsReadOnly;

public AddressBook getSelectedRecord() {
return selectedRecord;
}

public void setSelectedRecord(AddressBook selectedRecord) {
this.selectedRecord = selectedRecord;
}

public String getRecordMode() {
return recordMode;
}

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

public boolean isMakeAsReadOnly() {
return makeAsReadOnly;
}

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

@AfterCompose
public void initSetup(@ContextParam(ContextType.VIEW) Component view,
@ExecutionArgParam("selectedRecord") AddressBook addressBook,
@ExecutionArgParam("recordMode") String recordMode)
throws CloneNotSupportedException {
Selectors.wireComponents(view, this, false);
setRecordMode(recordMode);
CRUDService = (CRUDService) SpringUtil.getBean("CRUDService");

if (recordMode.equals("NEW")) {
this.selectedRecord = new AddressBook();
}

if (recordMode.equals("EDIT")) {
this.selectedRecord = addressBook;
}

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

@Command
public void saveThis() {
Map<String, Object> args = new HashMap<String, Object>();
CRUDService.save(this.selectedRecord);
args.put("selectedRecord", this.selectedRecord);
args.put("recordMode", this.recordMode);
BindUtils.postGlobalCommand(null, null, "refreshList", args);
win.detach();
}

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

That’s all. Now you can select the file “AddressList.zul” and right click,Select “Run on Server” (Using tomcat as web server). The output will be as follows
image


image


In the next article, we will see how to change the look and feel by override default ZK CSS.

Read More
Posted in ZK Spring | No comments

Wednesday, 27 February 2013

ZK MVVM CRUD With Spring 3 + JPA + Hibernate 4 Entity Manager–Part 5

Posted on 10:17 by Unknown

DAO and Service Layer for CRUD operation.

In the Part 4 article, we have seen how to integrate spring and hibernate. Now we create the DAO and service layer for the CRUD Operation.

Step 1:
First the Delete Package named “AddressBook” which is created by default. Now Select “Java” folder and right click, Select New –> Other-> Package and enter the Package name as “addressbook.dao” as shown.
image

Select the “dao” package, right click, select New –> Other->Interface as shown here
image

Enter the interface name as “CRUDDao” as shown.
image
image
We will write our DAO interface as generic, so that in the future we can use for any CRUD screen.

package addressbook.dao;

import java.util.List;

public interface CRUDDao {

<T> List<T> getAll(Class<T> klass);

<T> T save(T t);

<T> void delete(T t);
}

Step 2:
Next we will create CRUDDao implementation class which will implement the above interface.
Select the “dao” package, right click, select New –> Other->class and enter the class name as CRUDDaoImpl.java
image
image
Here is the java class code.

package addressbook.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import org.springframework.stereotype.Repository;

@Repository
public class CRUDDaoImpl implements CRUDDao {

@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager em;

public EntityManager getEm() {
return em;
}

public void setEm(EntityManager em) {
this.em = em;
}

@SuppressWarnings("unchecked")
public <T> List<T> getAll(Class<T> klass) {
return em.createQuery("Select t from " + klass.getSimpleName() + " t")
.getResultList();
}

public <T> T save(T t) {
T newRecord = null;
newRecord = em.merge(t);
return newRecord;
}

public <T> void delete(T t) {
em.remove(em.merge(t));
em.flush();
}
}
Step 3:
Next we will create our service layer. Now Select “Java” folder and right click, Select New –> Other-> Package and enter the Package name as “addressbook.service” as shown.
image

Select the “service” package, right click, select New –> Other->Interface as shown here
image


Enter the interface name as “CRUDService” as shown.
image
Here is the interface code


package addressbook.service;

import java.util.List;

public interface CRUDService {
<T> List<T> getAll(Class<T> klass);

<T> T save(T t);

<T> void delete(T t);
}
Step 4:
Next we will create CRUDServiceImpl implementation class which will implement the above interface.
Select the “service” package, right click, select New –> Other->class and enter the class name as CRUDServiceImpl.java
image
Here is the Class code

package addressbook.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import addressbook.dao.CRUDDao;
@Service
public class CRUDServiceImpl implements CRUDService {


@Autowired
private CRUDDao CRUDDao;

@Transactional(readOnly = true)
public <T> List<T> getAll(Class<T> klass) {
return CRUDDao.getAll(klass);
}


@Transactional
public <T> T save(T t) {
T newRecord = null;
newRecord = CRUDDao.save(t);
return newRecord;
}

@Transactional
public <T> void delete(T t) {
CRUDDao.delete(t);
}
}

Step 4:
Next we will domain object for addressbook table in the database. Select “addressbook” package, right click, select new-> other->Package and enter the package name as”domain”

image

Now select the package “domain”, right click, select new-Other->Class and enter the class name as “AddressBook.java”


image


Here is the code for the same.


package addressbook.domain;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class AddressBook implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;

private String fullName;
private String address1;
private String address2;
private String city;
private String zipCode;
private String state;
private String email;
private String mobile;

public String getFullName() {
return fullName;
}

public void setFullName(String fullName) {
this.fullName = fullName;
}

public String getAddress1() {
return address1;
}

public void setAddress1(String address1) {
this.address1 = address1;
}

public String getAddress2() {
return address2;
}

public void setAddress2(String address2) {
this.address2 = address2;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getZipCode() {
return zipCode;
}

public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getMobile() {
return mobile;
}

public void setMobile(String mobile) {
this.mobile = mobile;
}

public long getId() {
return id;
}

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

}


That’s all. In the next article, we will create our Presentation layer using ZK Framework.

Read More
Posted in ZK Spring | No comments

Tuesday, 26 February 2013

ZK MVVM CRUD With Spring 3 + JPA + Hibernate 4 Entity Manager–Part 4

Posted on 10:17 by Unknown

Integrate Spring and Hibernate

In the Part 3 article, we have seen how to define the database connection, user name, password, etc using persistence.xml file

Next, we need to configure Spring and Hibernate using applicationcontext.xml file.

Step 1:
In the Project navigator, Select the WEB-INF Folder under the webapp folder and right click-> Select New->Other-> XML File
image

Click Next and enter the file name as applicationContext.xml(ofcourse, we can have any name for the file) as shown
image

image

Now go to the source mode of applicationContext.xml and copy the below code and paste it.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">


<!-- The LocalEntityManagerFactoryBean creates an EntityManagerFactory suitable for environments which solely use JPA for data access.
The factory bean will use the JPA PersistenceProvider autodetection mechanism (according to JPA's Java SE bootstrapping) and,
in most cases, requires only the persistence unit name to be specified:
-->

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="ZKExamples" />
</bean>


<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<!-- tell spring to use annotation based congfigurations -->
<!-- It allow us to use @Autowire, @Required and @Qualifier annotations. -->

<context:annotation-config />

<!-- tell spring where to find the beans -->
<!-- tells Spring to scan the code for injectable beans under the package (and all its subpackages) specified. -->
<!-- It allow @Component, @Service, @Controller, etc.. annotations. -->
<context:component-scan base-package="addressbook" />

<tx:annotation-driven transaction-manager="transactionManager" />

<!-- This will ensure that hibernate or jpa exceptions are automatically
translated into Spring's generic DataAccessException hierarchy for those
classes annotated with Repository -->

<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

<bean id="CRUDService" class="addressbook.service.CRUDServiceImpl" />

</beans>

Finally, we have to update web.xml that we are having the configuration file, so it has to compile first.
Include the following lines in the web.xml file.


	<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<!-- Loads the Spring web application context -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Spring filter -->
<filter>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

In next article, we will create DAO and service layer for the CRUD operation.

Read More
Posted in ZK Spring | No comments

Monday, 25 February 2013

ZK MVVM CRUD With Spring 3 + JPA + Hibernate 4 Entity Manager–Part 3

Posted on 10:17 by Unknown

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 all the necessary dependency required for this example.

Next, we need to configure the database to which we are going to connect to do our CRUD operation. So this file The persistence.xml file will contain database name, user name , password , etc.

In this post, we will see how to configure the database connection and how to configure the integration between hibernate and Spring.

What is persistence.xml file ?

The persistence.xml file is a standard configuration file in JPA. It has to be included in the META-INF directory inside the JAR file that contains the entity beans. The persistence.xml file must define a persistence-unit with a unique name in the current scoped classloader.

Now let us create our persistence.xml file.

Step 1:
In the Project navigator, under the folder “Main”, select new-> Folder and create a folder name “resource” as shown.
image
image

Now let us add this folder in the class path. In the Project navigator, select the addressbook project and right click and select “Properties”.

In the Properties window, Select “Java Build Path”  and in the source Tab, Click on Add folder
image

In the dialog, select the resource folder as shown.
image

After selecting, the source tab will look as follows
image

Next we will create another folder called META-INF under the resource folder as shown.
image

Step 2:
Now in the META-INT Folder, let me create the persistence.xml file
Select the META-INT Folder, and right click say New –> Other-> XML File
image

image

Here is the persistence.xml file content. You can copy and paste. But remember to change the databasename, username, password, etc according to your setup.

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="2.0">

<persistence-unit name="ZKExamples" >
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="1234" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.use_sql_comments" value="true" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/addressbook" />
</properties>
</persistence-unit>
</persistence>

The provider attribute specifies the underlying implementation of the JPA EntityManager. In this example, we will use Hibernate.
This is only place where we will say who is our JPA Vendor.


In next part 4, we will see how to integrate Spring and Hibernate.

Read More
Posted in ZK Spring | No comments

Sunday, 24 February 2013

ZK MVVM CRUD With Spring 3 + JPA + Hibernate 4 Entity Manager–Part 2

Posted on 10:16 by Unknown

Create ZK Application with Eclipse and Maven.

Step 1:
In the Eclipse IDE, select File-> New->Other-> and Enter “Maven” for the wizards search as shown here.
image

Step 2:
Click next and uncheck the option “Create a simple Project(Skip archetype selection) as shown here.
image

Step 3:
Click Next and in the Catalog filter, Select ZK and select “ZK-archetype-webapp” from the list as shown.
image

Step 4:
Click Next and Enter Group ID, Artifact ID and Package as “AddressBook”  and select the first entry in the list as shown here.
image
Step 5:
After clicking finish, the maven wizard will create the default project folder structure as follows.
image

Step 6:
Now let us update the POM.XML file. Double click on POM.xml and go to source mode.
1. First remove the ZK Eval Repository from the POM File. The following lines should be removed.

<repository>
<id>ZK EVAL</id>
<name>ZK Evaluation Repository</name>
<url>http://mavensync.zkoss.org/eval</url>
</repository>

2. We will add the dependency for Spring, Hibernate and Mysql. Here is the complete final POM.XML File.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>AddressBook</groupId>
<artifactId>AddressBook</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<zk.version>6.5.1</zk.version>
<commons-io>1.3.1</commons-io>
<maven.build.timestamp.format>yyyy-MM-dd</maven.build.timestamp.format>
<packname>-${project.version}-FL-${maven.build.timestamp}</packname>
</properties>
<packaging>war</packaging>
<name>The AddressBook Project</name>
<description>The AddressBook Project</description>
<licenses>
<license>
<name>GNU LESSER GENERAL PUBLIC LICENSE, Version 3</name>
<url>http://www.gnu.org/licenses/lgpl.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<repositories>
<repository>
<id>ZK CE</id>
<name>ZK CE Repository</name>
<url>http://mavensync.zkoss.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>zkmaven</id>
<name>ZK Maven Plugin Repository</name>
<url>http://mavensync.zkoss.org/maven2/</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkbind</artifactId>
<version>${zk.version}</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zul</artifactId>
<version>${zk.version}</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkplus</artifactId>
<version>${zk.version}</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zhtml</artifactId>
<version>${zk.version}</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io}</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.9.Final</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>

<!-- ZK 5 breeze theme <dependency> <groupId>org.zkoss.theme</groupId>
<artifactId>breeze</artifactId> <version>${zk.version}</version> <optional>true</optional>
</dependency> -->
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- Run with Jetty -->
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.10</version>
<configuration>
<scanIntervalSeconds>5</scanIntervalSeconds>
<stopKey>foo</stopKey>
<stopPort>9999</stopPort>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Compile java -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<!-- Build war -->
<plugin>
<artifactId>maven-war-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId>
<version>2.1.1</version>
</plugin>
<!-- Pack zips -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<id>webapp</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>AddressBook${packname}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>assembly/webapp.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

Next Part 3 , we will see how to configure the database, username, password, etc. using persistence.xml file.

Read More
Posted in ZK Spring | No comments

Friday, 8 February 2013

ZK Passing Parameter between two files using MVVM–Part 2

Posted on 17:32 by Unknown

Overview

This is the first series of articles about Passing parameter between two zul files using MVVM Design pattern.This article will focus on the how to pass values from the parent window to child window opened in modal mode.
ZK Version : ZK 6.5.0 CE

So What we are going to do ?
1. Assume that you have small screen with a button to show another screen which opened as modal.
2. Now on Clicking of the Button, we will show the Second screen and also we will pass some arguments to the destination window.
3. In this article, we will create the VM For child window and will receive the arguments in the VM and update the View
 
Step 1:
If you are new ZK, then first set the development environment by following this document.

Step 2:

Let us create the Project in eclipse. Click File -> New -> ZK Project . Let us name the project as ZKMVVMPassingParameter1

Step 3:
Now let us create a zul file in the name of ParentWindow.zul. This zul is pretty simple contains two labels with textboxes and one button. So on clicking the button, we will call another zul file and also we will also pass the value of the text boxes typed by the user.
<?page title="Parent Window" contentType="text/html;charset=UTF-8"?>
<zk>
    <window title="Parent Window" border="normal"
        apply="org.zkoss.bind.BindComposer"
        viewModel="@id('myvm') @init('com.demo.ParentVM')">
        <label value="First Name"></label>
        <separator></separator>
        <textbox id="firstName" value="@bind(myvm.firstName)"></textbox>
        <separator></separator>
        <label value="Last Name"></label>
        <separator></separator>
        <textbox id="lastName" value="@bind(myvm.lastName)"></textbox>
        <separator></separator>
        <button label="Show Window" id="showWindow"
            onClick="@command('showChildWindow')">
        </button>
    </window>
</zk>
Step 4:
Now we will add our VM to our Parentwindow.zul as follows. Create a package called "com.demo" and create a java file called "ParentVM.java" Now on button click, we will call the ChildWindow.zul with the arguments as shown here.

package com.demo;
 
import java.util.HashMap;
 
import org.zkoss.bind.annotation.Command;
import org.zkoss.zk.ui.Executions;
 
public class ParentVM {
 
    private String firstName;
    private String lastName;
 
    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;
    }
 
    @Command
    public void showChildWindow() {
        final HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("firstName", this.firstName);
        map.put("lastName", this.lastName);
        Executions.createComponents("ChildWindow.zul", null, map);
 
    }
 
}
Step 5:
Now let us create a zul file in the name of ChildWindow.zul. In this zul file also, we have two labels and two text boxes in which by default when this zul file is called we are going to receive the arguments and fill the values.

<?page title="Child Window" contentType="text/html;charset=UTF-8"?>
<zk>
    <window title="Child Window" id="childwindow" border="normal" mode="modal"
        apply="org.zkoss.bind.BindComposer"
        viewModel="@id('myvm') @init('com.demo.ChildVM')">
        <label value="First Name"></label>
        <separator></separator>
        <textbox id="firstName" value="@bind(myvm.firstName)"></textbox>
        <separator></separator>
        <label value="Last Name"></label>
        <separator></separator>
        <textbox id="lastName" value="@bind(myvm.lastName)"></textbox>
        <separator></separator>
        <button label="Close" onClick="childwindow.detach()"></button>
    </window>
</zk>
Step 6:
Now we will add our VM to our ChildWindow.zul as follows. Create a package called "com.demo" and create a java file called "ChildVM.java"


package com.demo;
 
import org.zkoss.bind.annotation.AfterCompose;
import org.zkoss.bind.annotation.ExecutionArgParam;
 
public class ChildVM {
 
    private String firstName;
    private String lastName;
 
    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;
    }
 
    @AfterCompose
    public void initSetup(@ExecutionArgParam("firstName") String firstName,
            @ExecutionArgParam("lastName") String lastName) {
        
        this.firstName = firstName;
        this.lastName = lastName;
        
    }
}

Step 7:
That’s all. Now you can run ParentWindow.zul and type some value for first and last Name and click the button to show the values in the childwindow.zul
1. Type some values for the text boxes
2. Click the button, now you can see the values are populated.

Project Structure
image

You can download the source here.
Online Demo here.


Reference
1. http://books.zkoss.org/wiki/ZK_Developer's_Reference/MVVM
2. http://books.zkoss.org/wiki/ZK%20Developer's%20Reference/MVVM/Syntax/ViewModel/@Command
3. http://books.zkoss.org/wiki/ZUML_Reference/EL_Expressions/Implicit_Objects/arg
4. http://books.zkoss.org/wiki/ZK%20Developer's%20Reference/MVVM/Syntax/ViewModel/@AfterCompose
Read More
Posted in ZK Calling Another ZUL | No comments
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • 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...
  • EDI 5010 Documentation 837 Professional - Loop 2010BB Payer Name
    2010BB Payer Name          In this loop, all the information will be taken from Insurance master screen. Take a look of our sample screen...
  • EDI 5010 Documentation–837 - BHT - Beginning of Hierarchical Transaction
    BHT – Beginning of Hierarchical Transaction Loop Seg ID Segment Name Format Length Ref# Req Value   BHT Beginning of Hier...
  • Hibernate Validator Example 2
    In this example, we will see some more validation constraints such as @email, @past, @length, etc. And also we will also define custom error...
  • ZK Passing Parameter between two files using MVVM–Part 1
    Overview This is the first series of articles about Passing parameter between two zul files using MVVM Design pattern .This article will fo...
  • MVVM Command annotation and Notify change example
    Here is an example, how to pass parameter on a zul through MVVM Command binding annotation. ZK URL http://books.zkoss.org/wiki/ZK%20Develo...
  • History of Present Illness
    HPI - One of the main component of Clinical History. What is an HPI ? The history of present illness (HPI) is a chronological description...
  • Patient Demographics
    Patient browse (search) is the key element for any EMR / PMS Software. In my past 15 years experience, i involved more than 5 times in desig...
  • ViewModel Class Java Annotation @Init, @NotifyChange, @Command
    In following sections we'll list all syntaxes that can be used in implementing a ViewModel and applying ZK bind annotation. The ZK binde...
  • Good Website Design Links
    Form Design Label Placement in Forms International Address Fields in Web Forms 40 Eye-Catching Registration Pages blog-comment-form-...

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)
    • ►  September (7)
    • ►  August (13)
    • ►  July (1)
    • ►  June (11)
    • ►  May (3)
    • ►  April (14)
    • ►  March (19)
    • ▼  February (21)
      • ZK MVVM CRUD With Spring 3 + JPA + Hibernate 4 Ent...
      • ZK MVVM CRUD With Spring 3 + JPA + Hibernate 4 Ent...
      • ZK MVVM CRUD With Spring 3 + JPA + Hibernate 4 Ent...
      • ZK MVVM CRUD With Spring 3 + JPA + Hibernate 4 Ent...
      • ZK MVVM CRUD With Spring 3 + JPA + Hibernate 4 Ent...
      • ZK Passing Parameter between two files using MVVM–...
      • ZK Passing Parameter between two files using MVVM–...
      • ZK Passing Parameter between two files using MVC a...
      • How to submit the claims after primary insurance ?
      • ZK Passing Parameter between two files using MVC -...
      • ZK Passing Parameter between two files using MVC -...
      • MVVM CRUD with Spring 3.1 and Hibernate 4 and ZK -...
      • ZK Passing Parameter between two files using MVC -...
      • Move List box item up and Down using MVC Design Pa...
      • MVVM CRUD with Spring 3.1 and Hibernate 4 and ZK -...
      • Move List box item up and Down using MVVM Design P...
      • MVVM CRUD with Spring 3.1 and Hibernate 4 and ZK -...
      • ZK Passing Parameter between two files using MVC -...
      • MVVM CRUD with Spring 3.1 and Hibernate 4 and ZK -...
      • ZK Passing Parameter between two files using MVC -...
      • MVVM CRUD with Spring 3.1 and Hibernate 4 and ZK -...
    • ►  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