Search code examples
jpaejbeclipselinkglassfish-3

Related entities not loaded - EAGER ignored?


Got GlassFish v3. I have an one-to-many entity. The problem is, that EclipseLink seems to ignore the fetch EAGER mode.

Here is my entities.

@Entity
public class Person implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @OneToMany(mappedBy = "person", fetch = FetchType.EAGER)
    private List<Hobby> hobbies;

    // getter and setter
}

A 1:n relationship

@Entity
public class Hobby
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;    

    private String name;

    @ManyToOne
    @JoinColumn
    private Person person;

    // getter and setter
}

And the bean

@javax.ejb.Remote
public interface Testing
{
    public void addTestData();
    public List<Person> getTestData();
}

@javax.ejb.Stateless
public class TestingBean implements Testing
{
    @javax.persistence.PersistenceContext
    private EntityManager entityManager;

    public void addTestData()
    {
        Person p = new Person();
        p.setName("JOE");
        entityManager.persist(p);

        Hobby h1 = new Hobby();
        h1.setName("h1");
        h1.setPerson(p);

        entityManager.persist(h1);              
    }

    public List<Person> getTestData()
    {
        TypedQuery<Person> gridQuery = entityManager.createQuery("SELECT e FROM Person e", Person.class);
        return gridQuery.getResultList();
    }
}

EDIT Client:

InitialContext context = new InitialContext();      
Testing test = (Testing)context.lookup("java:global/dst2_1/TestingBean");

test.addTestData();

for(Person p: test.getTestData()) {
    System.out.println(p.getName());
    for(Hobby b : p.getHobbys()) {                  
        System.out.println(b.getName());
    }
}

context.close();

Using MySQL - Storing the data works. But if I fetch the data only the person is returned - not hobbies. Coudld you tell me what is wrong in my code?

EDIT sorry have tried so many things ... The code shown as above produces:

Exception Description: An attempt was made to traverse a relationship using indirection that had a null Session. This often occurs when a n entity with an uninstantiated LAZY relationship is serialized and that lazy relationship is traversed after serialization. To avoid this issue, ins tantiate the LAZY relationship prior to serialization.

But the Person is returned correctly. Why does it specify LAZY while I am using EAGER?


Solution

  • You code looks correct. I can't see any way that the EAGER could be ignored.

    Are you sure you get the error with this attribute, not another one?

    Also ensure you recompile and deployed your code correctly. You most like have an old version deployed.