Tuesday, 26 February 2013

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

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

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


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"

<!-- 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"
<property name="persistenceUnitName" value="ZKExamples" />

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

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

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

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


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.

<!-- Loads the Spring web application context -->

<!-- Spring filter -->

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

No comments:

Post a Comment