Reputation: 1391
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
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
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:
Upvotes: 1