Apache wicket with Hibernate (Annotation) example. A step by step guide.

In this tutorial, let us see how to integrate Apache wicket with hibernate 4 and create an example application in eclipse. Before going to this tutorial, you can go through my earlier tutorial How to configure and build a Apache wicket hello world application in eclipse without using maven.

Integrating Apache wicket with Hibernate is very easy. In this tutorial, let us create a example user registration application using Apache wicket and Hibernate.

Tools used in this tutorial to configure Apache-wicket project

1. Apache Wicket 6.16
2. Hibernate 4
3. Java : Java 1.6 or above
4. Eclipse Kepler with Apache server

Jars used in this tutorial for starting this simple wicket project with Hibernate support.

wicket hibernate jar

 

Now let us see the steps for integrating Hibernate with Apache Wicket and building a sample application.

Step 1: Open eclipse and create a dynamic web project using File->New->Dynamic Web Project
give the project name WicketHibernateExample and then click next…and finish

The directory structure for the project in the eclipse is  given below.

project structure wicket hibernate

Step 2: Get all the jars mentioned above and copy to the WEB-INF\lib folder…

PART I : (Hibernate Part)

Step 3: Decide database, table and necessary fields for your application (In this example, I have created the table User with the below details for storing user registration details.

Database Name : Test
Table Name : User
Fields Used : regId, name, emailId, createdOn

mysql> desc user;
+———–+————–+——+—–+——————-+—————————–+
| Field | Type | Null | Key | Default | Extra |
+———–+————–+——+—–+——————-+—————————–+
| regid | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | NO | | NULL | |
| emailid | varchar(50) | YES | | NULL | |
| createdOn | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+———–+————–+——+—–+——————-+—————————–+

DDL for the above table :

CREATE TABLE user(regid INT NOT NULL AUTO_INCREMENT, name VARCHAR(100) NOT NULL, emailid varchar(50), createdOn timestamp, PRIMARY KEY ( regid ));
Step 4: Create Hibernate Configuration file (hibernate-cfg.xml) for configuring database (MySQL) connections.


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/test
</property>
<property name="connection.username">root</property>
<property name="connection.password">******</property>

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

<!-- Display all generated 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 class="com.javaonline.RegBean" />

</session-factory>

</hibernate-configuration> 

Please note the mapping class RegBean which is the persistent class for storing item details.

<mapping class=”com.javaonline.RegBean” />

Step 5 : Now Create the persistent (POJO) class (in our eg. RegBean) for mapping the table (Users) fields using JPA (Java Persistent Annotations).


package com.javaonline;

import java.io.Serializable;
import java.util.Date;

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

@Entity
@Table(name="user")
public class RegBean implements Serializable {

@Id
@GeneratedValue
@Column(name="regId")
private String regId="";
private String name;
private String emailId;

@Temporal(TemporalType.DATE)
@Column (name="createdOn")
private Date createdOn;

public Date getCreatedOn() {
return new Date();
//return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public String getRegId() {
return regId;
}
public void setRegId(String regId) {
this.regId = regId;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="emailId")
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}

} 

Step 6: Create HibernateUtil class to create session factory for database access

package util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}

}

Now Hibernate part is over. The Apache Wicket part starts here

PART II : (Apache Wicket Part)

WicketStarter.java
***************

Step 7: Create WicketStarter.java file for opening the welcome page as given below


package com.javaonline;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;

public class WicketStarter extends WebApplication
{
@Override
public Class<? extends WebPage> getHomePage()
{
return FirstPage.class;
}

@Override
public void init()
{
super.init();

}
}

Step 8: Create necessary Java class and html files for user input using wicket

RegistrationInputPage.java
***********************


package com.javaonline;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import com.javaonline.dao.RegistrationDAO;

public class RegistrationInputPage extends WebPage {
Form<?> form = null;
RegBean regBean= new RegBean();

public RegistrationInputPage(final PageParameters page) throws Exception {
super();
Label createdOn = new Label("createdOn",new PropertyModel(regBean, "createdOn"));
TextField name = new TextField("name",new PropertyModel(regBean, "name"));
TextField emailId = new TextField("emailId", new PropertyModel(regBean, "emailId"));
name.setRequired(true);
emailId.setRequired(true);

form = new Form("regForm") {

public void onSubmit() {

System.out.println("name = "+ regBean.getName());
System.out.println("email = "+ regBean.getEmailId());
System.out.println("createdon = "+ regBean.getCreatedOn());

page.add("name", regBean.getName());
page.add("email", regBean.getEmailId());
page.add("createdOn",regBean.getCreatedOn());
try {

RegistrationDAO RegistrationDao = new RegistrationDAO();
RegistrationDao.add(regBean);
setResponsePage(new Acknowledgement(page));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

};

form.add(createdOn);
form.add(name);
form.add(emailId);
add(form);

}
}

RegistrationInputPage.html
***********************


<html>
<head>
<title>Registration Form</title>
</head>
<body>
<form id="regForm1" method="get" wicket:id="regForm">
<fieldset>
<legend style="color: #F90">Fill your details</legend>
Registration Date : <span wicket:id="createdOn"></span><br/>
<span>Your Name: </span><input wicket:id="name" type="text" id="name1" /><br/>
<span>Email: </span><input wicket:id="emailId" type="text" id="email" /><br/>
<p>
<input type="submit" name="Submit" value="Submit"/>
</p>
</fieldset>
</form>
</body>
</html> 

Step 9: Create DAO class (RegistrationDAO) to save or update registration details using Hibernate session

RegistrationDAO.java
******************


import util.HibernateUtil;
import org.hibernate.Session;
import com.javaonline.RegBean;
public class RegistrationDAO extends HibernateUtil {

public RegBean add(RegBean reg) {
Session session = HibernateUtil.createSessionFactory().getCurrentSession();
session.beginTransaction();
session.saveOrUpdate(reg);
session.getTransaction().commit();
return reg;
}

}

Step 10: Create necessary Java class and html files for output (Acknowledegement) using wicket

Acknowledgement.java
********************

package com.javaonline;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.request.mapper.parameter.PageParameters;

public class Acknowledgement extends WebPage {

public Acknowledgement(final PageParameters page) throws Exception {

Label name = new Label("name", page.get("name"));
Label email = new Label("email", page.get("email"));
Label regDate = new Label("createdOn", page.get("createdOn"));

add(name);
add(email);
add(regDate);
}
}

Acknowledgement.html
********************

<html>
<body>
Your Details are registered with us with the following details. <br/>
<span>Registration Date & Time :</span><span wicket:id="createdOn"></span><br/>
<span>Name :</span><span wicket:id="name"></span><br/>
<span>Email :</span><span wicket:id="email"></span><br/>
</body>
</html> 

Step 11 : Create web.xml as given below

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

<display-name>Wicket and Hibernate</display-name>
<filter>
<filter-name>wicket.wickethibernate</filter-name>
<filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
<init-param>
<param-name>applicationClassName</param-name>
<param-value>com.javaonline.WicketStarter</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>wicket.wickethibernate</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app> 

The above web.xml is configured for the filter class (org.apache.wicket.protocol.http.WicketFilter) of any wicket application
Now compile and run the above application http://localhost:8080/WicketHibernateExample

Input:

hibernate wicket input

 

Output:

 

 

hibernate wicket output
mysql> select * from user;
+——-+——+—————+———————+
| regid | name | emailid | createdOn |
+——-+——+—————+———————+
| 1 | ddf | sdsd | 2014-11-09 17:14:23 |
| 2 | ABC | abc@gmail.com | 2014-11-09 17:23:21 |
+——-+——+—————+———————+

You may also like

Leave a Reply

1 Comment on "Apache wicket with Hibernate (Annotation) example. A step by step guide."


Guest
umesh
2 months 4 hours ago

could you like to share source code project?