gschambial
gschambial

Reputation: 1391

Fetch child entities when finding by a normal field in Spring Data JPA

I am using Spring Data JpaRepository to find List of entities matching a particular field. Consider the following code snippet:

Entity:

@Entity
@Table(name = "master")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Master implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id", nullable = false)
    private Long Id;

@NotNull
    @Column(name = "user_id", nullable = false)
    private String userId;

@OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="id", referencedColumnName="id", insertable=false, updatable=false)
    private Details Details;

Spring Data Custom JpaRepository:

public interface MasterRepository extends JpaRepository<Master,Long> {

    List<Master> findMasterByUserId(String userId);

}

When i am using findBookingMasterByUserId repository method to find all records with specific user id, I am getting the List of Master entity but I am not getting the Details entity that has id as foreign key in it.

However, I get all the dependent entities when I use out of the box findAll method of JpaRepository but with custom findMasterByUserId repository method, child entities are not being fetched eagerly.

Any type of help would be highly appreciated. Thanks!

Upvotes: -1

Views: 6961

Answers (2)

Cepr0
Cepr0

Reputation: 30319

You can use @EntityGraph in your repo to eagerly get associated data:

@EntityGraph(attributePaths = {"details"})
List<Master> findBookingMasterByUserId(String userId); 

P.S. Don't forget to change 'Details' field to details;

Upvotes: 4

Tanmay Delhikar
Tanmay Delhikar

Reputation: 1387

Your entity name is "Master" not "booking_master".

Change your method to:

List<Master> findByUserId(String userId);

Refer to below spring docs for more information on query creation mechanism for JPA.

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

Alternatively,

@Query("SELECT m FROM Master m WHERE m.userId = :userId")
List<Master> findByUserId(@Param("userId") String userId);

The query generation from the method name is a query generation strategy where the invoked query is derived from the name of the query method.

We can create query methods that use this strategy by following these rules:

  • The name of our query method must start with one of the following prefixes: find…By, read…By, query…By, count…By, and get…By.
  • If we want to limit the number of returned query results, we can add the First or the Top keyword before the first By word. If we want to get more than one result, we have to append the optional numeric value to the First and the Top keywords. For example, findTopBy, findTop1By, findFirstBy, and findFirst1By all return the first entity that matches with the specified search criteria.
  • If we want to select unique results, we have to add the Distinct keyword before the first By word. For example, findTitleDistinctBy or findDistinctTitleBy means that we want to select all unique titles that are found from the database.
  • We must add the search criteria of our query method after the first By word. We can specify the search criteria by combining property expressions with the supported keywords.
  • If our query method specifies x search conditions, we must add x method parameters to it. In other words, the number of method parameters must be equal than the number of search conditions. Also, the method parameters must be given in the same order than the search conditions.

Upvotes: 1

Related Questions