【问题标题】:how to make findby with composite key in spring data - jpa -hibernate ? @EmbeddedId如何在 spring data - jpa -hibernate 中使用复合键创建 findby ? @EmbeddedId
【发布时间】:2020-06-22 15:56:42
【问题描述】:
@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;
}

这是我的存储库。如何制作find方法?我对此一无所知

List<Map<String, Object>> findByAccountTransactionId_trxDate(String trxDate);

我试过“findByAccountTransactionId_trxDate”、“findByAccountTransactionIdTrxDate”、“findByIdTrxDate”...

【问题讨论】:

  • 请分享你的Repository整个界面

标签: hibernate jpa spring-data composite-key embeddable


【解决方案1】:

你可以这样写:

public interface TransactionRepository extends JpaRepository<Transaction, AccountTransactionId> {

    List<Map<String, Object>> findByTrxDateAndAcctNo(String trxDate, String acctNo);

}

【讨论】:

  • 你就是我等的那个
  • 查看以下示例了解更多详情:- callicoder.com/…
  • 据我所知这会抛出异常,因为类型 Transaction 没有属性 trxDate
【解决方案2】:

我建议看看骆驼案是否会有所改变;可能因此而无法工作。

其次,我希望该方法返回对象列表,而不是地图。在您的情况下,这是我期望的解决方案:

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);

}

【讨论】:

    【解决方案3】:

    你可以使用@IdClass (https://attacomsian.com/blog/spring-data-jpa-composite-primary-key)

    然后你可以在链接中传递示例中的类,它会是

    repository.findById(new AccoutId(accountno,accounttype)

    这对我有用

    【讨论】:

    • 能否请您删除链接并将您的答案放在这里?
    • 您可以使用@IdClass 然后您可以在链接中的示例中传递类,它将是 repository.findById(new AccoutId(accountno,accounttype) 这对我有用
    猜你喜欢
    • 2019-05-06
    • 1970-01-01
    • 2016-05-05
    • 2021-02-13
    • 2022-01-28
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多