---
title: "Struts 2 + Spring 2 + JPA 的配置补充"
author: "arthurln"
date: "2007-09-02T10:05:00Z"
tags: ["Ajax", "Hibernate", "JPA", "Spring", "Struts"]
categories: ["企业架构"]
slug: "struts-2-spring-2-jpa"
draft: false
lastmod: "2009-02-24T21:39:02Z"
id: 119468
url: "https://arthurln.iteye.com/blog/119468"
---

搭建方法主要参考struts2 guide中的Struts 2 + Spring 2 + JPA + AJAX([struts.apache.org/2.0.9/docs/struts-2-spring-2-jpa-ajax.html](http://struts.apache.org/2.0.9/docs/struts-2-spring-2-jpa-ajax.html))文档。

　　关于用到的类库和构建方法参考那篇文档即可。这里要补充一下，为了方便进行测试，最好把spring-mock.jar也加进来。这样就可以使用AbstractJpaTests对象了，可以很好支持对lazy-load的测试，下边是一个例子：

*测试基类：*

java 代码

1. import org.springframework.test.jpa.AbstractJpaTests;
2. public abstract class BaseJpaTestCase extends AbstractJpaTests {
3. protected String\[] getConfigLocations() {
4. return new String\[] {
5. "file:/WebAppRoot/WEB-INF/applicationContext.xml",
6. "file:/WebAppRoot/WEB-INF/applicationContext-service.xml" };
7. }
8. }

*具体的测试类：*

java 代码

01. public class UserRoleServiceTest extends BaseJpaTestCase {
02. private UserRoleService userRoleService;
03. public void setUserRoleService(UserRoleService userRoleService) {
04. this.userRoleService = userRoleService;
05. }
06. @Test
07. public void testRemove() {
08. UserRole entity = new UserRole("some role name");
09. userRoleService.save(entity);
10. UserRole persistedEntity = userRoleService.find(entity.getId());
11. assertEquals(entity.getName(), persistedEntity.getName());
12. userRoleService.remove(persistedEntity .getId());
13. assertNull(userRoleService.find(persistedEntity .getId()));
14. }
15. }

　　测试类不需要在spring配置文件中进行说明，service对象会被自动的注入，非常的方便。

　　以前用hibernate的时候，Spring提供了OpenSessionInViewFilter来解决在view层的lazy-load问题。而使用jpa进行封装之后，可以使用OpenEntityManagerInViewFilter来达到同样的目的。

*在web.xml中进行同样的配置即可：*

xml 代码

1. &lt;filter&gt;
2. &lt;filter-name&gt;entityManagerFilterfilter-name&gt;
3. &lt;filter-class&gt;org.springframework.orm.jpa.support.OpenEntityManagerInViewFilterfilter-class&gt;
4. filter&gt;
5. &lt;filter-mapping&gt;
6. &lt;filter-name&gt;entityManagerFilterfilter-name&gt;
7. &lt;url-pattern&gt;\*.actionurl-pattern&gt;
8. filter-mapping&gt;

　　使用JPA的确是一个不错的选择，现在系统已经可以完全和所使用的持久化框架脱离关系了，虽然我可能会一直是用hibernate，不过在将来多一个选择总是不会错的。