Ankit
Ankit

Reputation: 101

How to use part of composite key in JPA repository methods to fetch data?

I have a class Application with EmbeddedId and second column in embbbedID is forgein key and having many to one relationship with offer.

@Entity
   public class Application implements Serializable{

private Integer id;

@EmbeddedId
private MyKey mykey;

private String resume;

@Enumerated(EnumType.STRING)
@NotNull
private ApplicationStatus applicationStatus;

    @Embeddable
public class MyKey implements Serializable{

    private static final long serialVersionUID = 1L;
    @NotNull
    private String emailId;
    @ManyToOne(fetch = FetchType.LAZY)
    @NotNull
    private Offer offer;

in Offer class mapping is done on jobTitle.

 @Repository
interface ApplicationRepository extends JpaRepository <Application,MyKey>

{

List<Application> findAllByMyKey_Offer(String jobTitle);
}

Trying this but getting no success... I want to fetch All application regarding a specific jobTitle. What shud be my method name in ApplicationRepository class.

Upvotes: 1

Views: 1009

Answers (2)

Sofiane REBIB
Sofiane REBIB

Reputation: 105

Your methode name is wrong, the right one is findAllByMykey_Offer or findAllByMykeyOffer, as your field is named mykey.

As mentionned in the documentation https://docs.spring.io/spring-data/jpa/docs/2.1.0.RELEASE/reference/html/ using List<Application> findAllByMykey_Offer(String jobTitle); is better than List<Application> findAllByMykeyOffer(String jobTitle);

Upvotes: 2

Bahdan Shaleshka
Bahdan Shaleshka

Reputation: 11

With composite key, your field name should include name of the field of embedded id. In you case it would be like this (I haven't tested it)

List<Application> findAllByMykeyOffer(String jobTitle);

Notice that k is lower-case here, because your field in class Application is named mykey, not myKey

Upvotes: 1

Related Questions