Spring+jpa做单元测试,实体类配置了@oneToMany 出现“ no session or session was closed”的错误。要用什么方法解决啊,搜了一堆没有找到想要的答案。
没上WEB不要给我复制一堆在web.xml下配置的代码啊~~ 

解决方案 »

  1.   

    贴下那个实体类的代码。
    @Entity
    @Table(name = "Organization")
    public class Organization {
    @Id
    @GeneratedValue
    @Column(name = "OrganizationId")
    private int organizationId; @Column(name = "OrganizationName", length = 200)
    private String organizationName; @Column(name = "OrganizationDesc")
    private String organizationDesc; @Column(name = "OrganizationCode", length = 10)
    private String organizationCode; @ManyToOne(targetEntity = Organization.class)
    @JoinColumn(name = "Organization_ParentId")
    private Organization parent; @OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE,
    CascadeType.REFRESH }, fetch = FetchType.LAZY, mappedBy = "parent")
    private Set<Organization> children = new HashSet<Organization>();
    测试代码(部分)如下:        @Test
    public void testGetUser() {
    Organization organization = organizationService.getOrganization(1);
    Set<Organization> set = organization.getChildren();
    for (Organization o : set) {
    System.out.println(o.getOrganizationName());
    }
    }
      

  2.   

    你這是多對多自關聯,但是lazy為true,延遲加載,所以, Organization organization = organizationService.getOrganization(1);
    調用
    Set<Organization> set = organization.getChildren();
    之前,session已經關閉。
    把fetch = FetchType.LAZY 改成fetch = FetchType.EAGER
      

  3.   


    回楼上 我就想用lazy加载怎么实现呢? 如果在web上的话可以加上“openSessionInview”这句话来实现,
    但是不在web上的话呢?
      

  4.   

    也可以,写hql的时候,加上join fetch