Struts 2 + Spring 2 + JPA 的配置补充

  搭建方法主要参考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 代码
  1. import org.springframework.test.jpa.AbstractJpaTests;   
  2.   
  3. public abstract class BaseJpaTestCase extends AbstractJpaTests {   
  4.   
  5.  protected String[] getConfigLocations() {   
  6.   return new String[] {   
  7.     "file:/WebAppRoot/WEB-INF/applicationContext.xml",   
  8.     "file:/WebAppRoot/WEB-INF/applicationContext-service.xml" };   
  9.  }   
  10. }  

具体的测试类:

java 代码
  1. public class UserRoleServiceTest extends BaseJpaTestCase {   
  2.   
  3.     private UserRoleService userRoleService;   
  4.   
  5.     public void setUserRoleService(UserRoleService userRoleService) {   
  6.         this.userRoleService = userRoleService;   
  7.     }   
  8.   
  9.     @Test  
  10.     public void testRemove() {   
  11.         UserRole entity = new UserRole("some role name");   
  12.         userRoleService.save(entity);   
  13.         UserRole persistedEntity = userRoleService.find(entity.getId());   
  14.         assertEquals(entity.getName(), persistedEntity.getName());   
  15.         userRoleService.remove(persistedEntity .getId());   
  16.         assertNull(userRoleService.find(persistedEntity .getId()));   
  17.     }   
  18.   
  19. }  

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

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

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

xml 代码
  1. <filter>  
  2.     <filter-name>entityManagerFilterfilter-name>  
  3.     <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilterfilter-class>  
  4. filter>  
  5.   
  6. <filter-mapping>  
  7.     <filter-name>entityManagerFilterfilter-name>  
  8.     <url-pattern>*.actionurl-pattern>  
  9. filter-mapping>  

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值