0

出于某些测试目的,我试图让 JUnit 测试抛出 LazyInitializationException。

我的情况是我有 3 个实体

@Entity(name = "Role")
public class Role {
    @LazyCollection(LazyCollectionOption.TRUE)
    @ManyToMany(mappedBy = "roles", fetch=FetchType.LAZY)
    private Set<AppUser> appUsers;
    ...

}

@Entity(name = "Group")
public class Group {
    @LazyCollection(LazyCollectionOption.TRUE)
    @ManyToMany(mappedBy = "groups", fetch=FetchType.LAZY)
    private Set<AppUser> appUsers;
    ...
}

@Entity(name = "AppUser")
public class AppUser {
    @LazyCollection(LazyCollectionOption.TRUE)
    @ManyToMany(fetch= FetchType.LAZY)
    @JoinTable(name = "APPUSER_ROLE", joinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID"))
    private Set<Role> roles;
    ...

    @LazyCollection(LazyCollectionOption.TRUE)
    @ManyToMany(fetch= FetchType.LAZY)
    @JoinTable(name = "APPUSER_GROUP", joinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "GROUP_ID", referencedColumnName = "ID"))
    private Set<Group> groups;
    ...

} 

我生成了一些测试数据,其中所有这 3 个数据都与关系正确地保存在数据库中。然后我提交交易。

但随后我尝试使用相同的测试方法读取Role(基于 id),但我也读取了所有其他相关实体(似乎急切地加载)。为什么会这样?我怎么来LazyInitializationException

编辑:好的,我对一般描述不感兴趣,而是需要一个代码示例,因为我无法在我的情况下启动它。一般描述并不能解决我的问题。

4

2 回答 2

3

我怎样才能来到 LazyInitializationException?

当你有:

  1. 延迟加载的实体成员(例如 OneToMany 或 ManyToMany)
  2. 没有活动事务(实体已分离)
  3. 该成员尚未加载
  4. 您尝试访问实体成员,这应该会触发延迟加载,但这是不可能的,因为实体已分离
于 2012-11-12T10:35:02.223 回答
0

问题在于,即使我在测试方法中提交了事务,我也必须关闭 EntityManager 并再次重新打开它以LazyInitializationException在我的设置中触发。

最后我得到了以下实体代码:

@Entity(name = "Role")
public class Role {
    @ManyToMany(mappedBy = "roles")
    private Set<AppUser> appUsers;
    ...

}

@Entity(name = "Group")
public class Group {
    @ManyToMany(cascade = {CascadeType.PERSIST})
    @JoinTable(name = "GROUP_APPUSER", joinColumns = @JoinColumn(name = "GROUP_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID"))
    private Set<AppUser> appUsers;
    ...
}

@Entity(name = "AppUser")
public class AppUser {
    @ManyToMany(cascade = {CascadeType.PERSIST})
    @JoinTable(name = "APPUSER_ROLE", joinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID"))
    private Set<Role> roles;
    ...

    @ManyToMany(mappedBy = "appUsers")
    private Set<Group> groups;
    ...

} 

所以而不是:

Group <- AppUser -> Role

我有:

Group -> AppUser -> Role

即使很难,也没有必要,因为一开始就出现了延迟加载(Group -> AppUser)延迟问题。

而测试代码本身,最​​重要的部分是:

em.getTransaction().begin();
em.persist(group);
em.getTransaction().commit();
em.close();

// reinit em
...

// load group from DB and afterwards close em
em.close();
...
// following throws LazyInitializationException :)
group.getAppUsers().iterator().next();
于 2012-11-12T12:51:20.317 回答