
Hibernate services are separated in it's own layer. These services allow to persist
Business Java Objects and encapsulate database specific logic in one place reather then polluting
Business Java Objects with the logic that does not belong there.
For example the
Employee is a POJO that knows nothing about the database. All the database
hibernate/
spring work happens in
EmployeeService. The
EmployessService extends a base class
HibernateDaoSupport that declares
SessionFactory for
hibernate and comes from
spring framework. The methods of the EmployeeService are transactional, the transactions are enabled in
{dev_proto}/src/java/applicationContext.xml. Here is the example:
<!-- setting up an employeeService object with the hibernateTransactions enabled -->
<bean id="employeeServiceTarget" class="com.custommode.dal.example.EmployeeService">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean> <bean id="employeeService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="target">
<ref local="employeeServiceTarget"/>
</property>
<property name="proxyTargetClass">
<value>true</value>
</property>
<property name="transactionManager">
<ref bean="hibernateTxManager"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<!-- configuring hibernate transactions --> <bean id="hibernateTxManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
<property name="sessionFactory"><ref bean="sessionFactory"/></property>
</bean>Here is the example implementation of one of the service methods:
public Integer create(Employee pEmployee) {
getHibernateTemplate().save(pEmployee);
return pEmployee.getId();
} getHibernateTemplate method comes from the parent class. And the invocation of the
create method will participate in a global transaction if there is one, or will spawn a new transaction. We didn't have to write any transaction code -/- it was handled for us by the
spring framework. If we want to disable transactions or change some transactions attributes, all we have to do is to make changes to
applicationContext.xml file. All the database connection handling is done by the
spring framework as well. Because of this the developers do not have to worry about open/close connection. This makes code much more mainteinable.
To obtain an instance of the service in
Struts Actions we would have to use one of the
spring utility classes, for example:
EmployeeService employeeService =
(EmployeeService)
WebApplicationContextUtils.getWebApplicationContext(
servlet.getServletContext()).getBean("employeeService");