by IntelliBitz Technologies
http://www.intellibitz.com
Objective:
===========
Spring MVC + Hibernate JPA Integration
Pre-Requisites:
===============
NetBeans, Apache Derby, Apache Tomcat
Add the required Spring & Hibernate & JPA library jars
- spring, spring-aspects, aspectjweaver
- hibernate-annotations, hibernate-entitymanager,
hibernate3, ejb3-persistence, asm, c3p0, cglib, ehcache, javassist,
jboss-common, jta
- derbyclient, jstl, antlr, commons-collections, commons-logging,
dom4j
Ready to Go? Now follow these steps..
========================
1. CONFIGURATION FILES
========================
Under Web folder
WEB-INF
========
web.xml
========
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="2.4">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-intelligrade.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>intelligrade</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>intelligrade</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>
index.jsp
</welcome-file>
</welcome-file-list>
</web-app>
WEB-INF
=========================
intelligrade-servlet.xml
=========================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- ========================= MESSAGE SOURCE DEFINITION
========================= -->
<!-- View Resolver for JSPs -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="requestContextAttribute" value="rc"/>
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/home.html">homeController</prop>
</props>
</property>
</bean>
<bean id="homeController"
class="com.ibt.intelligrade.mvc.HomeController">
<!-- the view does not matter for spring mvc + jpa integration
test application -->
<property name="viewName" value="index"/>
</bean>
</beans>
WEB-INF
====================================
applicationContext-intelligrade.xml
====================================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!-- Spring JPA Entity Manager Factory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="IntelliGradePU"/>
</bean>
<!-- Spring JPA Transaction Manager -->
<bean id="txManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory"
ref="entityManagerFactory"/>
</bean>
<!-- JPA annotations bean post processor -->
<!-- Required to load the EntityManager in the DAO -->
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostPro-cessor"/
class="com.ibt.intelligrade.service.CourseDaoImpl"/>
<!-- SERVICE LAYER for Transaction Demaracation -->
<bean id="courseService"
class="com.ibt.intelligrade.service.CourseServiceImpl">
<property name="courseDao" ref="courseDao"/>
</bean>
<!-- AOP Transaction Injection -->
<aop:config>
<aop:pointcut id="courseServiceMethods"
expression="execution(*
com.ibt.intelligrade.service.CourseService.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-
ref="courseServiceMethods"/>
</aop:config>
<!-- Transaction Propogation advice for the SERVICE layer -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="persist*" propagation="REQUIRES_NEW"/>
<tx:method name="testSpringMvcJpaIntegration*"
propagation="REQUIRED"/>
<tx:method name="*" propagation="SUPPORTS" read-
only="true"/>
</tx:attributes>
</tx:advice>
</beans>
In Source folder..
Create an Persistence Unit configuration file called persistence.xml
- Name must be persistence.xml (the required META-INF folder will be
automatically created by NetBeans)
META-INF
================
persistence.xml
================
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/
persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="IntelliGradePU" transaction-
type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.url"
value="jdbc:derby://localhost:1527/sample"/>
<property name="hibernate.connection.driver_class"
value="org.apache.derby.jdbc.ClientDriver"/>
<property name="hibernate.connection.password" value="app"/
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/
value="3000"/>
<property name="hibernate.cache.provider_class"
value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.dialect"
value="org.hibernate.dialect.DerbyDialect"/>
<!-- SQL stdout logging -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>
<!-- Scan for annotated classes and Hibernate mapping XML
files -->
<property name="hibernate.archive.autodetection"
value="class, hbm"/>
</properties>
</persistence-unit>
</persistence>
==================
2. DOMAIN CLASSES
==================
Create the following Domain Classes
- We have 2 domain objects named 'Course.java' and
'QuestionBank.java'
============
Course.java
============
package com.ibt.intelligrade.domain;
import com.ibt.intelligrade.domain.QuestionBank;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name="course")
public class Course implements java.io.Serializable {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Basic()
private String name;
@Basic()
private String description;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private Set<QuestionBank> questionBanks = new
HashSet<QuestionBank> (10);
/** Creates a new instance of Course */
public Course() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<QuestionBank> getQuestionBanks() {
return questionBanks;
}
public void setQuestionBanks(Set<QuestionBank> questionBanks) {
this.questionBanks = questionBanks;
}
public String toString() {
String retValue;
retValue = " Course Id: " + getId()
+ " Course Name: " + getName()
+ " Course Description: " + getDescription();
return retValue;
}
QuestionBank.java
==================
package com.ibt.intelligrade.domain;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table(name="questionbank")
public class QuestionBank implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Basic()
private String name;
@Basic()
private String description;
@ManyToOne(fetch=FetchType.LAZY)
private Course parent;
/** Creates a new instance of QuestionBank */
public QuestionBank() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Course getParent() {
return parent;
}
public void setParent(Course parent) {
this.parent = parent;
}
public String toString() {
String retValue;
retValue = " QuestionBank Id: " + getId()
+ " QuestionBank Parent : " + getParent().getName()
+ " QuestionBank Name: " + getName()
+ " QuestionBank Description: " + getDescription();
return retValue;
}
3. Spring Service / DAO layer
===============================
===============
CourseDao.java
===============
package com.ibt.intelligrade.service;
import com.ibt.intelligrade.domain.Course;
import java.util.List;
public interface CourseDao {
void persist (Course course);
Course getReference (Course course);
List<Course> getAllCourse ();
void remove(Course crs);
CourseDaoImpl.java
===================
package com.ibt.intelligrade.service;
import com.ibt.intelligrade.domain.Course;
import java.util.List;
import javax.persistence.*;
import org.springframework.orm.jpa.support.JpaDaoSupport;
public class CourseDaoImpl
implements CourseDao{
@PersistenceContext()
private EntityManager entityManager;
/** Creates a new instance of CourseDaoImpl */
public CourseDaoImpl() {
}
public void persist (Course course)
{
getEntityManager().persist(course);
}
public Course getReference (Course course)
{
return getEntityManager().getReference(course.getClass(),
course.getId());
}
public List<Course> getAllCourse (){
return getEntityManager().createQuery("from
Course").getResultList();
}
public void remove(Course crs) {
getEntityManager().remove (crs);
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
CourseService.java
===================
package com.ibt.intelligrade.service;
import com.ibt.intelligrade.domain.Course;
import java.util.List;
public interface CourseService {
void persistCourse (Course course);
void testSpringMvcJpaIntegration();
CourseServiceImpl.java
=======================
package com.ibt.intelligrade.service;
import com.ibt.intelligrade.domain.Course;
import com.ibt.intelligrade.domain.QuestionBank;
import java.util.List;
import java.util.Set;
public class CourseServiceImpl implements CourseService{
private CourseDao courseDao;
/** Creates a new instance of CourseServiceImpl */
public CourseServiceImpl() {
}
public CourseDao getCourseDao() {
return courseDao;
}
public void setCourseDao(CourseDao courseDao) {
this.courseDao = courseDao;
}
public void persistCourse (Course course)
{
courseDao.persist (course);
}
// Business method.. Testing the JPA Integration through DAO
public void testSpringMvcJpaIntegration() {
// PERSIST COURSE
Course course = new Course();
course.setName("JAVA");
course.setDescription("JAVA Standard Edition");
persistCourse (course);
System.out.print("<br>");
System.out.println(" SAVED Course: "+course);
System.out.print("<br>");
// PERSIST COURSE WITH QUESTION BANK COLLECTION
QuestionBank questionBank = new QuestionBank();
questionBank.setName("Java Question Bank");
questionBank.setDescription("JAVA question bank descritpion");
questionBank.setParent(course);
course = courseDao.getReference(course);
course.getQuestionBanks().add(questionBank);
persistCourse (course);
System.out.print("<br>");
System.out.println(" SAVED Course with QuestionBank:
"+questionBank);
System.out.print("<br>");
// RETREIVE THE COURSE AND TEST IT
// DELETE THEM FINALLY
List<Course> courses = courseDao.getAllCourse();
for (Course crs : courses) {
System.out.print("<br>");
System.out.println(" RETREIVED Course: "+crs);
System.out.print("<br>");
Set<QuestionBank> qbs = crs.getQuestionBanks();
for (QuestionBank qb : qbs) {
System.out.print("<br>");
System.out.println(" QuestionBank: "+qb);
System.out.print("<br>");
}
// DELETE COURSE (AND THE QUESTION BANK COLLECTION)
courseDao.remove(crs);
System.out.print("<br>");
System.out.println("REMOVED Course: "+crs);
System.out.print("<br>");
}
}
4. The Spring Controller
=========================
====================
HomeController.java
====================
package com.ibt.intelligrade.mvc;
import com.ibt.intelligrade.domain.Course;
import com.ibt.intelligrade.domain.QuestionBank;
import com.ibt.intelligrade.service.CourseService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import
org.springframework.web.servlet.mvc.ParameterizableViewController;
import javax.persistence.*;
import java.util.*;
public class HomeController extends ParameterizableViewController {
/** Creates a new instance of HomeController */
public HomeController() {
}
protected ModelAndView handleRequestInternal(HttpServletRequest
request, HttpServletResponse response)
throws Exception {
CourseService courseService = (CourseService)
getWebApplicationContext().getBean("courseService");
courseService.testSpringMvcJpaIntegration();
return super.handleRequestInternal(request, response);
}
Spring MVC + JPA integration DONE!
**. Run your project and Enjoy!!
====================================
link:
http://www.intellibitz.com