做JUNIT时奇怪的org.hibernate.LazyInitializationException

时间:2015-06-11 09:54:45

标签: java spring hibernate junit

我正在为一个SSH项目做JUnit。 首先,我在执行@Test方法时遇到了org.hibernate.LazyInitializationException。我做了一些研究并解决了它。 我所做的是添加用于绑定会话资源的Setup和TearDown。

这两种方法是这样的:

@Before
public void setup(){
    System.out.println("Setup() running....");
    String filename = "WebContent\\WEB-INF\\classes\\applicationContext.xml";
    ctx = new FileSystemXmlApplicationContext(filename);
    sf = (SessionFactory) ctx.getBean("sessionFactory");
    Session s = sf.openSession();
    TransactionSynchronizationManager.bindResource(sf, new SessionHolder(s));
}

@After
public void tearDown(){
    System.out.println("TearDown() running....");
    SessionHolder holder = (SessionHolder)TransactionSynchronizationManager.getResource(sf);
    Session s = holder.getSession();
    s.flush();
    TransactionSynchronizationManager.unbindResource(sf);
    SessionFactoryUtils.closeSession(s);
}

private SessionFactory sf;
private ApplicationContext ctx;

然后我写了另一个方法,但是再次引发了这个异常!这很奇怪。我重新运行第一个测试方法,它的工作原理。但第二个没有。

第一种测试方法如下:

@Test
public void testFindAll() {
    UserGroupService userggroupService = (UserGroupService) ctx.getBean("UserGroupService");

    try {
        List groups = userggroupService.findAll();
        System.out.println(groups);
        if (groups != null){
            for (Object grp : groups){
                UserGroupBean group = (UserGroupBean) grp;
                System.out.printf("id=%d, name=%s, %d members\n", group.getId(), group.getName(), group.getMembers()==null?0:group.getMembers().size());
                if (group.getMembers() != null){
                    for(UserBean user: group.getMembers()){
                        System.out.printf("\tuser-%d, %s\n", user.getUserID(), user.getName());
                    }
                }
            }
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

第二种测试方法如下:

@Test
public void testDeleteRel() {
    String filename = "WebContent\\WEB-INF\\classes\\applicationContext.xml";
    ApplicationContext ctx = new FileSystemXmlApplicationContext(filename);

    UserGroupService service = (UserGroupService) ctx.getBean("UserGroupService");


    try {
        UserGroupBean userGroup = new UserGroupBean();
        userGroup.setId(1L);
        UserGroupBean group = (UserGroupBean) service.getUserGroup(userGroup);
        List<UserBean> members = group.getMembers();
        System.out.println(members.size()+" members");
    //  members.remove(0);
    //  service.updateUserGroup(group);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

PO代码如下:

@Entity
@Table(name = "UserGroupBean")
public class UserGroupBean implements UserGroup {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany(targetEntity = UserGroupBean.class, 
        cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @JoinTable(name = "UserGroupParents", joinColumns = { @JoinColumn(name = "group_id") }, inverseJoinColumns = { @JoinColumn(name = "parent_id") })
    //@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private List<UserGroupBean> parents;

    @ManyToMany(targetEntity = UserBean.class, 
        cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @JoinTable(name = "UserGroupMembers", joinColumns = { @JoinColumn(name = "group_id") }, inverseJoinColumns = { @JoinColumn(name = "user_id") })
    //@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private List<UserBean> members;

    // Getters and setters ...

我的问题是:为什么同样的@Before和@After代码,但只有1种方法可以运行良好?我错过了什么?

由于

2 个答案:

答案 0 :(得分:0)

如果我理解了你的要求,那么在你的第二个Test方法中,你会尝试再次初始化应用程序Context,尽管它已经在before()方法中初始化了。这不是在junit中启动spring上下文的有效方法。请参考可能解决您的示例: Spring Junit 要么 Spring Junit 2

答案 1 :(得分:0)

对于错误org.hibernate.LazyInitializationException使用

@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class TestAnything{
   ...
}