ZK and Hibernate Configuration for MySQL Database

ZK Version : ZK 7.0.2


In this post, we will see how to setup the XML configuration file to connect MySQL via Hibernate ORM.

Step 1:
Follow my earlier post to create ZK 7 Maven Project.

Step 2:
image
Double click the pom.xml file to add dependencies for Hibernate and MySQL

a) hibernate-core 4.3.5.Final
b) mysql-connector-java
c) Apache DBCP. For more information, please
check here

And also we are going to Manage Hibernate session via Spring.  For More information on Spring integration with hibernate, please read this article. So we will
add Spring ORM Dependencies as well.
Here is the complete POM.File after adding all necessary dependencies.
 

<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>ZK7Example1</groupId>
<artifactId>ZK7Example1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<zk.version>6.5.2</zk.version>
<commons-io>1.3.1</commons-io>
<spring.version>4.0.0.RELEASE</spring.version>
<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 ZK7Example1 Project</name>
<description>The ZK7Example1 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>
<repository>
<id>ZK EVAL</id>
<name>ZK Evaluation Repository</name>
<url>http://mavensync.zkoss.org/eval</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>

<!-- Hibernate -->

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>

<!-- MySQL database driver -->

<dependency> <!-- MySQL database driver -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.24</version>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>

<dependency> <!-- Apache BasicDataSource -->
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>

<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>


<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>


<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>


<dependency> <!-- Used for Hibernate4 LocalSessionFactoryBean -->
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</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.6</source>
<target>1.6</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>ZK7Example1${packname}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/main/assembly/webapp.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
 
Step 3:
Now let us setup our Spring XML Configuration. In our Project, location file web.xml (webapp->Web-inf) and add the following: Here is the complete web.xml after adding.

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<description><![CDATA[My ZK Application]]></description>
<display-name>ZK7Example1</display-name>



<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>


<!-- Spring can be easily integrated into any Java-based web framework.
All you need to do is to declare the ContextLoaderListener in your web.xml
and use a contextConfigLocation <context-param> to set which context files
to load. If you don't specify the contextConfigLocation context parameter,
the ContextLoaderListener will look for a /WEB-INF/applicationContext.xml
file to load. Once the context files are loaded, Spring creates a WebApplicationContext
object based on the bean definitions and puts it into the ServletContext. -->

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
classpath:applicationContext_hib.xml
classpath:springOrmContext.xml
</param-value>
</context-param>
<!-- Loads the Spring web application context -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>



<!-- ====================================================== -->
<!-- SPRING REQUEST LISTENER -->
<!-- ====================================================== -->
<listener>
<display-name>Spring Request Context Listener</display-name>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>



<!-- //// -->
<!-- ZK -->
<listener>
<description>ZK listener for session cleanup</description>
<listener-class>org.zkoss.zk.ui.http.HttpSessionListener</listener-class>
</listener>
<servlet>
<description>ZK loader for ZUML pages</description>
<servlet-name>zkLoader</servlet-name>
<servlet-class>org.zkoss.zk.ui.http.DHtmlLayoutServlet</servlet-class>

<!-- Must. Specifies URI of the update engine (DHtmlUpdateServlet). It
must be the same as <url-pattern> for the update engine. -->
<init-param>
<param-name>update-uri</param-name>
<param-value>/zkau</param-value>
</init-param>
<!-- Optional. Specifies whether to compress the output of the ZK loader.
It speeds up the transmission over slow Internet. However, if you configure
a filter to post-processing the output, you might have to disable it. Default:
true <init-param> <param-name>compress</param-name> <param-value>true</param-value>
</init-param> -->
<!-- [Optional] Specifies the default log level: OFF, ERROR, WARNING, INFO,
DEBUG and FINER. If not specified, the system default is used. <init-param>
<param-name>log-level</param-name> <param-value>OFF</param-value> </init-param> -->
<load-on-startup>1</load-on-startup><!-- Must -->
</servlet>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zul</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zhtml</url-pattern>
</servlet-mapping>
<!-- [Optional] Uncomment it if you want to use richlets. <servlet-mapping>
<servlet-name>zkLoader</servlet-name> <url-pattern>/zk/*</url-pattern> </servlet-mapping> -->
<servlet>
<description>The asynchronous update engine for ZK</description>
<servlet-name>auEngine</servlet-name>
<servlet-class>org.zkoss.zk.au.http.DHtmlUpdateServlet</servlet-class>

<!-- [Optional] Specifies whether to compress the output of the ZK loader.
It speeds up the transmission over slow Internet. However, if your server
will do the compression, you might have to disable it. Default: true <init-param>
<param-name>compress</param-name> <param-value>true</param-value> </init-param> -->
<!-- [Optional] Specifies the AU extension for particular prefix. <init-param>
<param-name>extension0</param-name> <param-value>/upload=com.my.MyUploader</param-value>
</init-param> -->
</servlet>
<servlet-mapping>
<servlet-name>auEngine</servlet-name>
<url-pattern>/zkau/*</url-pattern>
</servlet-mapping>

<!-- [Optional] Uncomment if you want to use the ZK filter to post process
the HTML output generated by other technology, such as JSP and velocity.
<filter> <filter-name>zkFilter</filter-name> <filter-class>org.zkoss.zk.ui.http.DHtmlLayoutFilter</filter-class>
<init-param> <param-name>extension</param-name> <param-value>html</param-value>
</init-param> <init-param> <param-name>compress</param-name> <param-value>true</param-value>
</init-param> </filter> <filter-mapping> <filter-name>zkFilter</filter-name>
<url-pattern>your URI pattern</url-pattern> </filter-mapping> -->
<!-- //// -->

<!-- ///////////// -->
<!-- DSP (optional) Uncomment it if you want to use DSP However, it is turned
on since zksandbox uses DSP to generate CSS. <servlet> <servlet-name>dspLoader</servlet-name>
<servlet-class>org.zkoss.web.servlet.dsp.InterpreterServlet</servlet-class>
<init-param> <param-name>class-resource</param-name> <param-value>true</param-value>
</init-param> </servlet> <servlet-mapping> <servlet-name>dspLoader</servlet-name>
<url-pattern>*.dsp</url-pattern> </servlet-mapping> -->

<!-- /////////// -->
<!-- [Optional] Session timeout -->
<session-config>
<session-timeout>60</session-timeout>
</session-config>

<!-- [Optional] MIME mapping -->
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
<mime-mapping>
<extension>gif</extension>
<mime-type>image/gif</mime-type>
</mime-mapping>
<mime-mapping>
<extension>htm</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>html</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jpeg</extension>
<mime-type>image/jpeg</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jpg</extension>
<mime-type>image/jpeg</mime-type>
</mime-mapping>
<mime-mapping>
<extension>js</extension>
<mime-type>text/javascript</mime-type>
</mime-mapping>
<mime-mapping>
<extension>pdf</extension>
<mime-type>application/pdf</mime-type>
</mime-mapping>
<mime-mapping>
<extension>png</extension>
<mime-type>image/png</mime-type>
</mime-mapping>
<mime-mapping>
<extension>txt</extension>
<mime-type>text/plain</mime-type>
</mime-mapping>
<mime-mapping>
<extension>xls</extension>
<mime-type>application/vnd.ms-excel</mime-type>
</mime-mapping>
<mime-mapping>
<extension>xml</extension>
<mime-type>text/xml</mime-type>
</mime-mapping>
<mime-mapping>
<extension>zhtml</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>zul</extension>
<mime-type>text/html</mime-type>
</mime-mapping>

<welcome-file-list>
<welcome-file>index.zul</welcome-file>
<welcome-file>index.zhtml</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>

Please note in the above file, we have specified three files to include the configuration via XML Files. The files are applicationContext.xml,  applicationContext_hib.xml and springOrmContext.xml.  Next step is to create all those files.
Step 4:
We will create a folder called resource and we will create all the three XML Configuration files.  In the Eclipse Navigator , right click on the Project->Main folder and select New –> Folder and enter the folder name as “resource”.  Now right click on Project and select Properties. In the Properties window, select Java Build Path

Select “Source Tab” and Click “Add Folder” and check the resource folder.

image


Step 5:
Next we will create applicationContext.xml in the resource folder. Select resource folder and right click, Select New –> Other –> XML File

image
Enter the file name as “applicationContext.xml”. Copy the below into newly created XML File

image

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

<!-- ====================================================== -->
<!-- Define the property placeholder configurer -->
<!-- ====================================================== -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>


</beans>

Please Note that, in the above file, we have included one more file called jdbc.properties.  This is the file where we are going to say what is the MySQL database name,u
u
ser name and password. We will create this file later. So basically this XML Configuration file used to configure our data source (i,e) MySQL in our example. 

Step 6:
Next on the resource folder, we will create the another XML Configuration file (applicationContext_hib.xml) for Hibernate Properties. Here is the content of the
applicationContext_hib.xml file.
image



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



<!-- Define the datasource; define the session factory, we need specify
the packagesToScan property, this property will scan all entity annotated
class. define the context component-scan basepackage, this will scan all
@Repository annotated Class -->

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.example.domain" />

<property name="hibernateProperties">
<props>
<prop key="configurationClass">org.hibernate.cfg.AnnotationConfiguration</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.zeroDateTimeBehavior">convertToNull</prop>
<prop key="hibernate.connection.zeroDateTimeBehavior">convertToNull</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
</props>
</property>
</bean>
</beans>



Please Note that, in the above file, we have used packagesToScan property of the SessionFactory to dynamically pick up entity classes and set up the sessionFactory.
You can see that, we are going to create all our entity classes in the package com.example.domain.


Step 7:
Next step to create Spring – Hibernate integration XML Configuration file springOrmContext.xml.
image

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

<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>


<!-- Container Configuration: The IOC container configuration xml file is
shown below,The container has the <context:component-scan> element and <context:annotation-config/>
<context:annotation-config/> used to intimate the beans of this IOC container
are annotation supported. By pass the base path of the beans as the value
of the base-package attribute of context:component-scan element, we can detect
the beans and registering their bean definitions automatically without lots
of overhead. The value of base-package attribute is fully qualified package
name of the bean classes. We can pass more than one package names by comma
separated -->

<context:annotation-config />
<context:component-scan base-package="com.example.business" />

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

<!-- 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="com.example.business.service.CRUDServiceImpl" />
</beans>

Normally you declare all the beans or components in XML bean configuration file, so that Spring container can detect and register your beans or components.
Actually, Spring is able to auto scan, detect and instantiate your beans from pre-defined project package, no more tedious beans declaration in in XML file. So here
we said to auto detect in com.example.business  package
.
Step 8:
Now let us create database called “zkexamples” and table called “member”. Here is the table structure.
/*
SQLyog Ultimate v11.3 (64 bit)
MySQL - 5.0.41-community-nt : Database - zkexamples
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`zkexamples` /*!40100 DEFAULT CHARACTER SET latin1 */;

USE `zkexamples`;

/*Table structure for table `member` */

DROP TABLE IF EXISTS `member`;

CREATE TABLE `member` (
`ID` bigint(20) NOT NULL auto_increment,
`code` varchar(50) default NULL,
`lastName` varchar(100) default NULL,
`firstName` varchar(100) default NULL,
`gender` varchar(10) default NULL,
`DOB` date default NULL,
`mobileNo` varchar(20) default NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

Insert some records. here is the insert into script


INSERT INTO member(CODE,lastname,firstName, gender,DOB,mobileNo) VALUES('PJ4990015','Javier','Perez','Male','1965-12-12','3112123123')
INSERT INTO member(CODE,lastname,firstName, gender,DOB,mobileNo) VALUES('FS41100045','Simmons','Foster','Male','1967-12-12','5434343333')
INSERT INTO member(CODE,lastname,firstName, gender,DOB,mobileNo) VALUES('DH41111395','HanaMeal','David','Female','1956-03-22','4234343433')
INSERT INTO member(CODE,lastname,firstName, gender,DOB,mobileNo) VALUES('MP41121203','PATRICK','MICHEL','Male','1989-09-09','7234343466')
INSERT INTO member(CODE,lastname,firstName, gender,DOB,mobileNo) VALUES('DJ41290900','Jody','Dianna','Female','2012-12-12','3432123213')

Step 9:
Now let us create our entity class for the table member. As we said earlier, we will create this class in the package called “com.example.domain”. Create this package and class Member as shown here.
image

package com.example.domain;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "member")
public class Member {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long ID;
private String code;
private String firstName;
private String lastName;
private String gender;
@Temporal(TemporalType.DATE)
private Date DOB;
private String mobileNo;

public long getID() {
return ID;
}

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

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

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 String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public Date getDOB() {
return DOB;
}

public void setDOB(Date dOB) {
DOB = dOB;
}

public String getMobileNo() {
return mobileNo;
}

public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}

}
 
Step 10:
Next we will create our DAO Layer. Select the java folder and right click, Select New –> Other->Package and enter the package name as com.example.business.dao. After package is created, select the package dao and right click, select New-> Other->Interface and enter the interface name as “CRUDDao”

image

package com.example.business.dao;

import java.io.Serializable;
import java.util.List;

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

<T> void Save(T klass);

<T> T findByPrimaryKey(Class<T> klass, Serializable id);

<T> T GetUniqueEntityByNamedQuery(String query, Object... params);

<T> List<T> GetListByNamedQuery(String query, Object... params);

<T> void delete(T klass);

<T> Long getQueryCount(String query, Object... params);
}
 


Step 11:
Now let us create the DAO Class which implement the above interface. Select the package dao and right click, select New-> Other->class  and enter the class name as "CRUDDaoImpl” as shown

image

package com.example.business.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

@Repository
public class CRUDDaoImpl implements CRUDDao {

@Autowired
SessionFactory sessionFactory;

@SuppressWarnings("unchecked")
public <T> List<T> getAll(Class<T> klass) {
return getCurrentSession().createQuery("from " + klass.getName())
.list();
}

protected final Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}

public <T> void Save(T klass) throws DataAccessException {
getCurrentSession().saveOrUpdate(klass);
}

public <T> void delete(T klass) throws DataAccessException {
getCurrentSession().delete(klass);

}

/**
* Retrieve an object that was previously persisted to the database using
* the indicated id as primary key
*/
@SuppressWarnings("unchecked")
public <T> T findByPrimaryKey(Class<T> klass, Serializable id) {
return (T) getCurrentSession().get(klass, id);
}

@SuppressWarnings("unchecked")
public <T> List<T> GetListByNamedQuery(String query, Object... params) {
Query q = getCurrentSession().getNamedQuery(query);

int i = 1;
String arg = "arg";
if (params != null) {
for (Object o : params) {
if (o != null) {
q.setParameter(arg + i, o);
i++;
}
}
}

List<T> list = (List<T>) q.list();
return list;
}

@SuppressWarnings("unchecked")
public <T> T GetUniqueEntityByNamedQuery(String query, Object... params) {

Query q = getCurrentSession().getNamedQuery(query);

int i = 1;
String arg = "arg";
for (Object o : params) {
q.setParameter(arg + i, o);
i++;
}

List<T> results = q.list();

T foundentity = null;
if (!results.isEmpty()) {
// ignores multiple results
foundentity = results.get(0);
}
return foundentity;
}

public <T> Long getQueryCount(String query, Object... params) {

Query q = getCurrentSession().getNamedQuery(query);
int i = 1;
String arg = "arg";
Long count = (long) 0;

if (params != null) {
for (Object o : params) {
if (o != null) {
q.setParameter(arg + i, o);
i++;
}
}
}
count = (Long) q.uniqueResult();
return count;
}
}

Hibernate 4 provides a feature called "contextual Sessions", where Hibernate itself manages one current Session per transaction. This is roughly equivalent to Spring's synchronization of one Hibernate Session per transaction.The main advantage of this DAO style is that it depends on Hibernate API only; no import of any Spring class is required.
For more information, Please refer the following links
1. The Persistence Layer with Spring 3.1 and Hibernate
2. Spring Integration with Hibernate
3. Implementing DAOs based on plain Hibernate 3 API
Step 12:
Next we will create our Service Layer. Select the java folder and right click, Select New –> Other->Package and enter the package name as com.example.business.service. After package is created, select the package service and right click, select New-> Other->Interface and enter the interface name as “CRUDService”

image

package com.example.business.service;

import java.io.Serializable;
import java.util.List;

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

<T> void Save(T klass);

<T> T findByPrimaryKey(Class<T> klass, Serializable id);

<T> void delete(T klass);

public <T> T GetUniqueEntityByNamedQuery(String query, Object... params);

<T> List<T> GetListByNamedQuery(String query, Object... params);

<T> Long getQueryCount(String query, Object... params);
}

Step 13:
Now let us create the Service Class which implement the above interface. Select the package service and right click, select New-> Other->class and enter the class name as "CRUDServiceImpl” as shown

image

package com.example.business.service;

import java.io.Serializable;
import java.util.List;

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

import com.example.business.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> void Save(T klass) throws DataAccessException {
CRUDDao.Save(klass);
}

@Transactional
public <T> void delete(T klass) throws DataAccessException {
CRUDDao.delete(klass);
}

@Transactional
public <T> T GetUniqueEntityByNamedQuery(String query, Object... params) {
return CRUDDao.GetUniqueEntityByNamedQuery(query, params);
}

@Transactional
public <T> List<T> GetListByNamedQuery(String query, Object... params) {
return CRUDDao.GetListByNamedQuery(query, params);
}

@Override
@Transactional(readOnly = true)
public <T> Long getQueryCount(String query, Object... params) {
return CRUDDao.getQueryCount(query, params);
}

@Override
@Transactional(readOnly = true)
public <T> T findByPrimaryKey(Class<T> klass, Serializable id) {
return CRUDDao.findByPrimaryKey(klass, id);
}

}

Step 14:
Next step is to create our jdbc.properties where we will define the MySQL connectivity information. In the resource folder, create a file called jdbc.properties as shown.

image

Here is the content of that file

#################################################################
# MYSQL #
#################################################################
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/zkexamples?zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=1234
hibernate.dialect=org.hibernate.dialect.MySQLDialect

#################################################################
# Hibernate Query Debug output in the console #
#################################################################
hibernate.show_sql=false
hibernate.format_sql=true

Step 15

It is time to test all our stuffs. Before running the application, make sure the following items.
1. In the Eclipse markers window, make sure there are no error message.
2. DAO Layer classes should be created in package com.example.business.dao;
3. Service Layer Classes should be created in package com.example.business.service.
4. Database Entity classes should be created in package com.example.domain;

Here is the Overall Project Structure.

image

When creating ZK Maven Project, by default index.zul and corresponding VM Class MyViewModel.java will be created as shown here

 image
Double click MyViewModel and replace with the following content. Here we are just retrieving the all the records from the member table and
showing the total number of records in ZK Messagebox.

package ZK7Example1;

import java.util.List;

import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Messagebox;

import com.example.business.service.CRUDService;
import com.example.domain.Member;

public class MyViewModel {

@WireVariable
protected CRUDService crudService;

private int count;

@Init
public void init() {
count = 100;
}

@Command
@NotifyChange("count")
public void cmd() {
crudService = (CRUDService) SpringUtil.getBean("CRUDService");
List<Member> allReordsInDB=null;
allReordsInDB = crudService.getAll(Member.class);
Messagebox.show("Total Records : " + allReordsInDB.size());
++count;
}

public int getCount() {
return count;
}
}

Now select the project and run. On clicking of the button, you should see the following output

image

You can download the source here