Skip to content
Advertisement

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

I have a class with embedded Id

@Entity
@Table(name="account_table")
Public class AccountLink {

@EmbeddedId
private AccountLinkKey accountLinkKey;
//Rest of code
}

@Embeddable
Public class AccountLinkKey {
//Rest code here

@ColumnName(name="i am hiding")
private String segAccount;

@ColumnName(name="i am hiding")
private String secAccount;
//Rest of code
}

Now in my repository I want to have a method to search only by secAccount, so how should I write findBy..

List<AccountLink> findBy...(String secAccount); 

I tried findByAccountLinkKeySecAccount(String secAccount) but still no success.

Advertisement

Answer

I have rewritten your class and could add repository function as well. Here’s my implementation which you might consider taking a look at.

Here’s the class AccountLink.java.

@Entity
@Table(name = "account_table")
public class AccountLink {

    @Column(name = "id")
    public Long id;

    @EmbeddedId
    private AccountLinkKey accountLinkKey;

    @Embeddable
    public class AccountLinkKey {
        @Column(name = "seg_account")
        private String segAccount;

        @Column(name = "sec_account")
        private String secAccount;
    }
}

And the AccountLinkRepository.java.

public interface AccountLinkRepository extends JpaRepository<AccountLink, Long> {
    AccountLink findAccountLinkByAccountLinkKey_SecAccount(String secAccount);
}

I have added an id column in the AccountLink class as the primary key of the account_table. You might need something like this as well for your table.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement