0 Replies Latest reply on Jan 11, 2008 8:05 PM by jfrankman

    @ManyToOne uses eager fetching even if FetchType.LAZY used

    jfrankman Novice

      I have a many one to relationship and when I run a query to fetch the objects selected in the query, the related objects are still fetched even though the FetchType is lazy. Here are the mappings:

      PolicyVO class maps to the FBWorker class:

      public class PolicyVO implements Serializable
      {
       @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "AGENT", nullable = true, referencedColumnName="AGENTNO" )
       public FBWorker getAgent() {
       return agent;
       }
      }
      FBWorker class maps to the PolicyVO class:
      public class FBWorker implements Serializable
      {
       @Id @Column(name="ID")
       public Long getId()
       {
       return id;
       }
      
       @OneToMany(fetch=FetchType.LAZY,mappedBy="agent")
       public List<PolicyVO> getAgentPolicies()
       {
       return agentPolicies;
       }
      }

      Then I run the following JPA query:
      select policy from PolicyVO policy


      Watching the logs I see that first a query is run that selects the policy data from the database. Then, after the query is complete a query to the FBWorker table is generated and ran for every single policy object. Of course, this is unacceptable. I thought that if FetchType.Lazy is specified that the related class would not be loaded until the accessor method is called. Is there something wrong with the above mappings that makes lazy fetching impossible? I just need to fetch the PolicyVO objects without the extra overhead of fetching the related FBWorker objects.

      I should also mention that the "agent" foreign key in the PolicyVO data does not map to the Primary Key of the FBWorker data, it only maps to a field (agentno) that is also unique. I know this is sloppy, but I am dealing with some legacy data here.