rodney757
rodney757

Reputation: 583

default to join fetch for child entities in spring data jpa

I am using spring data jpa and hibernate.

When I fetch an entity, multiple select statements are being issued to fetch the relationships.

Is there a way to instruct spring data jpa to always use joins when possible?

Ex. entities:

@Entity
public class Parent {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private long id;

   @Temporal(TemporalType.TIMESTAMP)
   private Date ts;

   @OneToMany(fetch=FetchType.LAZY, mappedBy="parent") 
   private List<Child> child;
}

child:

@Entity
public class Child {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private long id;

   @ManyToOne
   @JoinColumn(name="parentId", referencedColumnName="parentId")
   private Parent parent;
}

Upvotes: 1

Views: 2440

Answers (1)

Argb32
Argb32

Reputation: 1405

The fetch type of the child relationship is specified to be Lazy. That instructs not to load the relationship with parent entity. Try Eager fetch type.

If you want the fetch type to be lazy you can decrease number of statements by using @BatchSize on Child (Children?) mapping.

Upd:

As the problem is when Child entity is fetched Entity graph should help. Declare it:

@NamedEntityGraph(
name = "child.withParent",
attributeNodes = {
        @NamedAttributeNode("parent")
}

)

And use with a repository method:

@EntityGraph("child.withParent")
Child findWithParentById(Long id);

Upvotes: 1

Related Questions