ITeye博客

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

arthurln · 2007-09-02 10:05 · miscellany · 企业架构 · Ajax · Spring · JPA · Struts · Hibernate · Markdown

搭建方法主要参考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. 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 代码

  1. public class UserRoleServiceTest extends BaseJpaTestCase {
  2. private UserRoleService userRoleService;
  3. public void setUserRoleService(UserRoleService userRoleService) {
  4. this.userRoleService = userRoleService;
  5. }
  6. @Test
  7. public void testRemove() {
  8. UserRole entity = new UserRole("some role name");
  9. 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. <filter>
  2. <filter-name>entityManagerFilterfilter-name>
  3. <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilterfilter-class>
  4. filter>
  5. <filter-mapping>
  6. <filter-name>entityManagerFilterfilter-name>
  7. <url-pattern>*.actionurl-pattern>
  8. filter-mapping>

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

评论(4)

  1. #4 楼 · arthurln · 2007-12-19 20:29

    JPA是一个标准,标准就意味着很多地方难以设计的足够精巧,JPA很多默认配置与Hibernate是不一样,还是需要它的各个实现版本的扩展。尽量还是用Hibernate吧。

    不灵活是一定的,不过个人喜欢这种与特定框架解耦的感觉。就像jdbc,虽然牺牲了部分灵活性,却带来了巨大的好处。

  2. #3 楼 · allenny · 2007-09-28 23:06

    allenny writes:

    按照这篇文章配置,我碰到了一个问题:文章里说将service从构造函数注入Action中,但是我运行后Struts报错说必须要有无参数的构造函数,我加了无参数构造函数后,service就空指针,说明action并没有从Spring初始化,不知道是什么原因。是不是什么地方没配好?

    解决了,原来struts.xml里action的class要配成Spring里的bean的名称!唉,配置如何能做到“强类型”啊

  3. #2 楼 · kyo100900 · 2007-09-28 18:20
  4. #1 楼 · allenny · 2007-09-28 18:06

    按照这篇文章配置,我碰到了一个问题:文章里说将service从构造函数注入Action中,但是我运行后Struts报错说必须要有无参数的构造函数,我加了无参数构造函数后,service就空指针,说明action并没有从Spring初始化,不知道是什么原因。是不是什么地方没配好?

评论功能维护中,当前仅展示历史评论。