how i can use jpa inner fetch join in jpa repository?

Viewed 87

I'm trying to use spring data jpa. If I'm calling findById, fetch join is working. but If I'm not using an id condition(ex) findByMemberId, fetch join is not working.

I'm trying to entitygraph but, i want to use inner fetch join.

how i can use jpa fetch join?

here is my code.

@Getter
@Setter
@Entity
public class Delivery {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    private Long memberId;

    @ManyToOne(fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "order_id")
    private Order order;
...
...
}

@Getter
@Setter
@Entity
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
...
...
}

DeliveryRepository.java

@Repository
public interface DeliveryRepository extends JpaRepository<Delivery, Long> {
     Optional<Gift> findByMemberId(Long MemberId);
}

Service

...
deliveryRepository.findById(1L); // fetch join working
deliveryRepository.findByMemberId(1234L); // fetch join not working
...
1 Answers

For derived queries Spring Data JPA constructs an explicit query. Therefore the fetch configuration from annotations don't apply. Defining and applying an entity graph to the method should allow you to get the fetch strategy you desire.

See https://www.baeldung.com/spring-data-jpa-named-entity-graphs for an example how to do that.

Related