'how to make findby with composite key in spring data - jpa -hibernate ? @EmbeddedId
@Embeddable
public class AccountTransactionId implements Serializable {
private String trxDate;
private String acctNo;
private int trxNo;
}
@Entity
public class Transaction {
@EmbeddedId
private AccountTransactionId accountTransactionId;
private int amt;
private int fee;
private String cancelYn;
}
this is my repository. how to make the find method? i don't have any idea about that
List<Map<String, Object>> findByAccountTransactionId_trxDate(String trxDate);
i tried "findByAccountTransactionId_trxDate", "findByAccountTransactionIdTrxDate", "findByIdTrxDate"...
Solution 1:[1]
I suggest having a look over the camel case if will change something; probably there is going to not work because of that.
Second, I would expect the method to return a list of objects, instead of a map. In your case, this is the solution I expect to work:
public interface TransactionRepository extends JpaRepository<Transaction, AccountTransactionId> {
/**
* here rename accountTransactionId to id
* and trxDate to trxdate
*/
List<Object> findByIdTrxdate(String trxDate, String acctNo);
List<Object> findByAccountTransactionIdTrxDate(String trxDate, String acctNo);
}
Solution 2:[2]
You can write like this:
public interface TransactionRepository extends JpaRepository<Transaction, AccountTransactionId> {
List<Map<String, Object>> findByTrxDateAndAcctNo(String trxDate, String acctNo);
}
Solution 3:[3]
You could use @IdClass (https://attacomsian.com/blog/spring-data-jpa-composite-primary-key)
Then you can just pass the class in the example in the link, it would be
repository.findById(new AccoutId(accountno,accounttype)
This worked for me
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Radu Linu |
Solution 2 | Umang Soni |
Solution 3 | alex |