搭建方法主要参考struts2 guide中的Struts 2 + Spring 2 + JPA + AJAX(struts.apache.org/2.0.9/docs/struts-2-spring-2-jpa-ajax.html)文档。
关于用到的类库和构建方法参考那篇文档即可。这里要补充一下,为了方便进行测试,最好把spring-mock.jar也加进来。这样就可以使用AbstractJpaTests对象了,可以很好支持对lazy-load的测试,下边是一个例子:
测试基类:
java 代码
- import org.springframework.test.jpa.AbstractJpaTests;
-
- public abstract class BaseJpaTestCase extends AbstractJpaTests {
-
- protected String[] getConfigLocations() {
- return new String[] {
- "file:/WebAppRoot/WEB-INF/applicationContext.xml",
- "file:/WebAppRoot/WEB-INF/applicationContext-service.xml" };
- }
- }
具体的测试类:
java 代码
- public class UserRoleServiceTest extends BaseJpaTestCase {
-
- private UserRoleService userRoleService;
-
- public void setUserRoleService(UserRoleService userRoleService) {
- this.userRoleService = userRoleService;
- }
-
- @Test
- public void testRemove() {
- UserRole entity = new UserRole("some role name");
- userRoleService.save(entity);
- UserRole persistedEntity = userRoleService.find(entity.getId());
- assertEquals(entity.getName(), persistedEntity.getName());
- userRoleService.remove(persistedEntity .getId());
- assertNull(userRoleService.find(persistedEntity .getId()));
- }
-
- }
测试类不需要在spring配置文件中进行说明,service对象会被自动的注入,非常的方便。
以前用hibernate的时候,Spring提供了OpenSessionInViewFilter来解决在view层的lazy-load问题。而使用jpa进行封装之后,可以使用OpenEntityManagerInViewFilter来达到同样的目的。
在web.xml中进行同样的配置即可:
xml 代码
- <filter>
- <filter-name>entityManagerFilterfilter-name>
- <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilterfilter-class>
- filter>
-
- <filter-mapping>
- <filter-name>entityManagerFilterfilter-name>
- <url-pattern>*.actionurl-pattern>
- filter-mapping>
使用JPA的确是一个不错的选择,现在系统已经可以完全和所使用的持久化框架脱离关系了,虽然我可能会一直是用hibernate,不过在将来多一个选择总是不会错的。