HIbernate - JSP/Servlet Simple Example

Tuesday, June 15, 2010 Posted by Sanka Senevirathna 0 comments
HIbernate - JSP/Servlet Simple Example

You can download full code example from here.

This example use Hibernate 3.5 and JPA 2.0 Annotatyion base classes.
You can see how to use JPA entities as HIbernate entities.

This example use Derby database.


hibernate-configuration file is as Following


This example is using annotated entity classes that genarated from eclipse.So no need to write xml mapping files for each entity.











jdbc:derby://localhost:1527/catalogueDB;create=true
org.apache.derby.jdbc.ClientDriver
app
app






thread


org.hibernate.dialect.DerbyDialect

create
org.hibernate.cache.NoCacheProvider
true
org.hibernate.transaction.JDBCTransactionFactory













package com.snk.model;


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

// Generated May 30, 2009 6:49:31 AM by Hibernate Tools 3.2.4.GA

/**
* This class contains the course details.
*
*/
@Entity
public class Course implements java.io.Serializable {

@Id
@GeneratedValue
private long courseId;
@Column
private String courseName;

public Course() {
}

public Course(String courseName) {
this.courseName = courseName;
}

public long getCourseId() {
return this.courseId;
}

public void setCourseId(long courseId) {
this.courseId = courseId;
}

public String getCourseName() {
return this.courseName;
}

public void setCourseName(String courseName) {
this.courseName = courseName;
}

}


package com.snk.frontend;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.snk.controler.ServiceLocator;
import com.snk.model.Course;


/**
* Servlet implementation class View
*/
/**
* @author Administrator
*
*/
public class View extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public View() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("sanka do get");
doPorocess(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("sanka do post");
doPorocess(request, response);
}


protected void doPorocess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
ServiceLocator obj = new ServiceLocator();
out.println("Before Insert three records\n");
Long courseId1 = obj.saveCourse("Physics");
Long courseId2 = obj.saveCourse("Chemistry");
Long courseId3 = obj.saveCourse("Maths");

showCourse(obj.listCourse(),out);
out.println("End of Insert three records\n\n\n\n");
obj.updateCourse(courseId3, "Mathematics");
showCourse(obj.listCourse(),out);
out.println("End of update three records\n\n\n\n");
obj.deleteCourse(courseId2);
out.println("End of delete chemistry records\n\n\n\n");
showCourse(obj.listCourse(),out);

}

private void showCourse(List courses,PrintWriter out)
{
for (Iterator iterator = courses.iterator(); iterator.hasNext();)
{
Course course = (Course) iterator.next();
out.println("Cource name : "+course.getCourseName());
}
}

}




package com.snk.controler;
import java.util.List;
import java.util.Iterator;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.snk.model.Course;
import com.snk.util.HibernateUtil;

public class ServiceLocator {


public Long saveCourse(String courseName)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
Long courseId = null;
try {
transaction = session.beginTransaction();
Course course = new Course();
course.setCourseName(courseName);
courseId = (Long) session.save(course);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return courseId;

/* //Following Are the code in JPA for insert query
EntityManagerFactory emf=Persistence.createEntityManagerFactory("hibernate-servlet");
EntityManager em=emf.createEntityManager();
Course course = new Course();
course.setCourseName(courseName);
course.setCourseId(200);
Long courseId = 200L;
em.persist(course);
System.out.println("Afetr Save");*/


}

public List listCourse()
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
List courses = session.createQuery("from Course").list();
for (Iterator iterator = courses.iterator(); iterator.hasNext();)
{
Course course = (Course) iterator.next();
System.out.println(course.getCourseName());
}
transaction.commit();
return courses;
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
return null;
} finally {
session.close();
}
}

public void updateCourse(Long courseId, String courseName)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Course course = (Course) session.get(Course.class, courseId);
course.setCourseName(courseName);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

public void deleteCourse(Long courseId)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Course course = (Course) session.get(Course.class, courseId);
session.delete(course);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

}


package com.snk.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// sessionFactory = new Configuration().configure().buildSessionFactory();//Default configuration
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();//Annotation Configuration

} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}







hibernate-servlet

index.jsp




View
View
com.snk.frontend.View


View
/View



Labels: , ,

Spring BlazeDS Integration

Tuesday, June 1, 2010 Posted by Sanka Senevirathna 0 comments

Spring BlazeDS Integration






1. Configuring and Using the BlazeDS


MessageBroker with Spring



MessageBroker is the heart of the Spring BlazeDS Integration.
When HTTP messages come from Flex client will be routed through the
Spring DispatcherServlet to the Spring-managed MessageBroker.

There is no need to configure the BlazeDS MessageBrokerServlet when using the
Spring-managed MessageBroker.





2. Configuring the Spring DispatcherServlet


web.xml is the heart of the j2ee web project.So we have to configure it because
each an every request is map to web.xml.

The DispatcherServlet must be configured in web.xml to bootstrap a Spring
WebApplicationContext. For example:





Spring MVC Dispatcher Servlet
org.springframework.web.servlet.DispatcherServlet

contextConfigLocation
/WEB-INF/config/web-application-config.xml

1



3. Configuring the MessageBroker in Spring


A simplified Spring XML config namespace is provided for configuring the MessageBroker in
your WebApplicationContext. To use the namespace support you must add the schema location
in your Spring XML config files. A typical config will look something like the following:




...



Following XML config namespace tags makes the Spring BlazeDS Integration configuration tags available under the flex
namespace in your configuration files. The above setup will be assumed for the rest of the
configuration examples to follow. For the full detail of every attribute and tag available in the



config namespace, be sure to refer to the spring-flex-1.0.xsd as every element and attribute is
fully documented there. Using an XSD-aware XML editor such as the one in Eclipse should
bring up the documentation automatically as you type.

At a minimum, the MessageBrokerFactoryBean must be configured as a bean in your
Spring WebApplicationContext in order to bootstrap the MessageBroker, along with a
MessageBrokerHandlerAdapter and an appropriate HandlerMapping (usually a
SimpleUrlHandlerMapping) to route incoming requests to the Spring-managed
MessageBroker.

These beans will be registered automatically by using the provided message-broker tag in
your bean definition file. For example, in its simplest form:






This will set up the MessageBroker and necessary supporting infrastructure using sensible
defaults. The defaults can be overriden using the provided attributes of the message-broker
tag and its associated child elements. For example, the default location of the BlazeDS XML
configuration file (/WEB-INF/flex/services-config.xml) can be overridden using the
services-config-path attribute. The MessageBrokerFactoryBean uses Spring's
ResourceLoader abstraction, so that typical Spring resource paths may be used. For
example, to load the configuration from the application's classpath:



The equivalent MessageBrokerFactoryBean definition using vanilla Spring configuration
would be:








Note especially that with the message-broker tag, it is not necessary to assign a custom id to
the MessageBroker, and it is in fact discouraged so that you won't have to continually reference
it later. The only reason you would ever need to provide a custom id is if you were bootstrapping
more than one MessageBroker in the same WebApplicationContext.
Labels: , , ,