Step 2.Generate Spring ORM classes
Time to complete this step: 10 minutes
In this step, you will use the Spring Generate ORM Classes wizard fordefining/creating the service interfaces and data access object (DAO) classes for the Department entity as shown below:
You will perform following tasks in this step:
- Generate Spring ORM classes for the Department entity
- Review the generated Spring Service bean and DAO classes
Generate Spring ORM classes for the Department entity
-
In the
Project Explorer view, right-click the
TroubleTicketSystemServer project and select
Spring > Generate Spring ORM Classes...from the context menu.
Notice that the Spring bean configuration file field has been created when you added the Spring facet to the project. If you wish to use another file, click the Manage Spring bean configuration... link, and then make your selection. For this tutorial, we will just use the Spring bean configuration file generated during the previous step.
-
Click the
Add
button to add a new Spring ORM service for the
DepartmentJPA entity.
- Enter DepartmentDelegate as the service name.
- Select the TroubleTicketSystemServer as the persistence unit.
- This will show a list of ORM entities managed by the TroubleTicketSystemServer persistence unit. Select the com.oracle.ticketsystem.beans.Department entity.
- For the
Service interface , click the
Browse..
button and select the
com.oracle.ticketsystem.delegates package. Specify
IDepartmentDelegate as the service interface name.
- For the
Service class, click the
Browse..
button and select the
com.oracle.ticketsystem.delegates.impl package. Specify
DepartmentSpringDelegate as the serviceclass name.
- Forthe
DAO interface, click the
Browse..
button and select the
com.oracle.ticketsystem.dao package. Specify
IDepartmentDao asDAO interface name.
- Forthe
DAO class, click the
Browse..
button and select the
com.oracle.ticketsystem.dao.impl package. Specify
DepartmentJPADao asDAOclass name.
- Click OK.
-
Verify that the
New Spring ORM Classes > Spring Services Definition dialog correctly displays the service name and the entity that you selected in the previous step, and then click
Next. This will open the
New Spring ORM Classes > Implementation Strategy wizard page.
- Select the Use plain JPA for DAO implementation and click Finish.
- That generates the Spring service and DAO classes for the
Department JPA entityin the packages specified. The Spring bean classes contain methods for standard create, read, update, and delete operations.
Note that only the DAO implementation class is dependent on a specific framework. This lets you change ORM frameworks quickly, without rewriting client code. -
The Spring beans used to access the JPA entities are generated into
com.oracle.ticketsystem.delegate and
com.oracle.ticketsystem.delegate.impl packages.Open the
TroubleTicketSystemServer >WebContent > WEB-INF > applicationContext.xml Spring Configuration file and review its content.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><beans xmlns=" http://www.springframework.org/schema/beans" xmlns:tx=" http://www.springframework.org/schema/tx" xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--bean post-processor for JPA annotations--> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"> </bean> <!--Exception translation bean post processor--> <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"> </bean> <!--Transaction manager for a single JPA EntityManager (alternative to JTA)--> <bean class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" id=" entityManagerFactory"> <property name=" persistenceUnitName" value=" TroubleTicketSystemServer"/> </bean> <bean class="org.springframework.orm.jpa.JpaTransactionManager" id=" transactionManager"> <property name=" entityManagerFactory" ref=" entityManagerFactory"/> </bean> <!-- enable the configuration of transactional behavior based on annotations --> <tx:annotation-driven transaction-manager="transactionManager"/> <bean class="com.oracle.ticketsystem.delegates.impl.DepartmentSpringDelegate" id="DepartmentDelegateService"> <property name=" dao"> <bean class=" com.oracle.ticketsystem.dao.impl.DepartmentJPADao"/> </property> </bean> </beans>The Spring configuration file is configured with beansthatarepost-processor for JPA annotations and exception translation. It also configures the JPA entity manager factory beanthat depends on the persistence unit name.
Since, we areusing the local resource-level transactions provided by the JPA entity manager, so the transaction manager bean has been defined and bound it to the JpaTransactionManager class.
Also, a DepartmentDelegateService bean is defined, which is intialized withthe JPA DAO for Department entity.
-
Open the
IDepartmentDelgate.java file.It has methods to persist/delete a
Department entity and find specific or all
Departmententities.
-
Also, open the
DepartmentSpringDelegate.java file under the
com.oracle.ticketsystem.delegates.impl package.
package com.oracle.ticketsystem.delegates.impl; import java.util.List; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.context.ApplicationContext; import com.oracle.ticketsystem.beans.Department; import com.oracle.ticketsystem.delegates.IDepartmentDelegate; import com.oracle.ticketsystem.dao.IDepartmentDao; /** * The service class for the Department entity. */ @Transactional(propagation=Propagation.REQUIRED) public class DepartmentSpringDelegate implements IDepartmentDelegate { /** * The dao instance injected by Spring. */ private IDepartmentDao dao; /** * The service Spring bean id, used in the applicationContext.xml file. */ private static final String SERVICE_BEAN_ID = "DepartmentDelegateService"; public DepartmentSpringDelegate() { super(); } /** * Returns the singleton <code>IDepartmentDelegate</code> instance. */ public static IDepartmentDelegate getInstance(ApplicationContext context) { return (IDepartmentDelegate)context.getBean(SERVICE_BEAN_ID); } /** * Find an entity by its id (primary key). * @return The found entity instance or null if the entity does not exist. */ @Transactional(propagation=Propagation.NEVER, readOnly=true) public Department findDepartmentById(long id) throws Exception { try { return getDao().findDepartmentById(id); } catch (RuntimeException e) { throw new Exception("findDepartmentById failed with the id " + id + ": " + e.getMessage()); } } /** * Return all persistent instances of the <code>Department</code> entity. */ @Transactional(propagation=Propagation.NEVER, readOnly=true) public List<Department> findAllDepartments() throws Exception { try { return getDao().findAllDepartments(); } catch (RuntimeException e) { throw new Exception("findAllDepartments failed: " + e.getMessage()); } } /** * Make the given instance managed and persistent. */ public void persistDepartment(Department department) throws Exception { try { getDao().persistDepartment(department); } catch (RuntimeException e) { throw new Exception("persistDepartment failed: " + e.getMessage()); } } /** * Remove the given persistent instance. */ public void removeDepartment(Department department) throws Exception { try { getDao().removeDepartment(department); } catch (RuntimeException e) { throw new Exception("removeDepartment failed: " + e.getMessage()); } } /** * Called by Spring using the injection rules specified in * the Spring beans file "applicationContext.xml". */ public void setDao(IDepartmentDao dao) { this.dao = dao; } public IDepartmentDao getDao() { return this.dao; } }Using Spring, the transaction can be started and committed (or rolled back) at method entry and exit. This is done by annotating the bean class or method with the @Transactional annotation.
A field of type IDepartmentDao and corresponding getter/setter methods have been provided. The setDao(IDepartmentDao) method will be called by Spring using the injection rule specified in the Spring configuration (applicationContext.xml) file.
-
Open the
IDepartmentDao.java file under the
com.oracle.ticketsystem.dao package. This interface defines the methods for performing CRUD operations on the
Department entity.
-
Open the
DepartmentJPADao.java file under the
com.oracle.ticketsystem.dao.impl package. This class uses the JPA API for performing CRUD operations on the
Department entity.
package com.oracle.ticketsystem.dao.impl; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.oracle.ticketsystem.beans.Department; import com.oracle.ticketsystem.dao.IDepartmentDao; import org.springframework.stereotype.Repository; /** * The DAO class for the Department entity. */ @Repository public class DepartmentJPADao implements IDepartmentDao { @PersistenceContext private EntityManager em; public DepartmentJPADao() { super(); } /** * Return the persistent entities returned from a named query. */ public List findByNamedQuery(String queryName) { Query queryObject = em.createNamedQuery(queryName); return queryObject.getResultList(); } /** * Return the persistent entities returned from a named query with named parameters. */ public List findByNamedQuery(String queryName, String[] paramNames, Object[] paramValues) { if (paramNames.length != paramValues.length) { throw new IllegalArgumentException(); } Map<String, Object> params = new java.util.HashMap<String, Object>(paramNames.length); for (int i = 0; i < paramNames.length; ++i) { params.put(paramNames[i], paramValues[i]); } Query queryObject = em.createNamedQuery(queryName); if (params != null) { for (Map.Entry<String, ?> entry : params.entrySet()) { queryObject.setParameter(entry.getKey(), entry.getValue()); } } return queryObject.getResultList(); } /** * Find an entity by its id (primary key). * @return The found entity instance or null if the entity does not exist. */ public Department findDepartmentById(long id) { return (Department)em.find(Department.class, new Long(id)); } /** * Return all persistent instances of the <code>Department</code> entity. */ @SuppressWarnings("unchecked") public List<Department> findAllDepartments() { try { String jpqlString = "select department from " + Department.class.getSimpleName() + "department"; Query query = em.createQuery( jpqlString ); return query.getResultList(); } finally { if (em != null) { em.close(); } } } /** * Make the given instance managed and persistent. */ public void persistDepartment(Department department) { em.persist(em.merge(department)); } /** * Remove the given persistent instance. */ public void removeDepartment(Department department) { /*In JPA, objects detach automatically when they are serialized or when a persistence context ends. The merge method returns a managed copy of the given detached entity.*/ em.remove(em.merge(department)); } }The @Repository annotation indicates that an annotated class is a "Repository" or ("DAO").
The em field of type EntityManager will get injected by Spring. The entity manager injectedhas beenconfigured into the applicationContext.xml file and the persistence unit referred is defined and configured in the JPA persistence.xml configuration file.
On the New ORM Service dialog, provide the following information:
button to add a new Spring ORM service for the
DepartmentJPA entity.
button and select the
com.oracle.ticketsystem.delegates package. Specify
IDepartmentDelegate as the service interface name.