【问题标题】:Search by two entities doesn't work with JpaRepository按两个实体搜索不适用于 JpaRepository
【发布时间】:2020-01-26 12:42:39
【问题描述】:

我正在制作一个应用程序,其中包含一个包含许多交易的钱包的用户配置文件。

这是 Transaction 类:

@Entity
@Table(name = "transactions")
public class Transaction extends BaseEntity {

    @Column(name = "amount", nullable = false)
    private BigDecimal amount;

    @Column(name = "executed_on", nullable = false)
    private LocalDateTime executedOn;

    @Column(name = "is_top_up")
    private boolean isTopUp;

    @Column(name = "note")
    private String note;

    @ManyToOne(targetEntity = UserProfile.class)
    private UserProfile sender;

    @ManyToOne(targetEntity = UserProfile.class)
    private UserProfile receiver;

    public Transaction() {
    }

这是 Wallet 类

@Entity
@Table(name = "wallets")
public class Wallet extends BaseEntity {

    @ManyToMany(targetEntity = Transaction.class, cascade = {
            CascadeType.PERSIST,
            CascadeType.MERGE
    }, fetch = FetchType.EAGER)
    @JoinTable(name = "wallets_transactions",
            joinColumns = @JoinColumn(name = "wallet_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "transaction_id", referencedColumnName = "id")
    )
    private Set<Transaction> transactions;

    public Wallet() {
        this.transactions = new HashSet<>();
    }

    public Set<Transaction> getTransactions() {
        return transactions;
    }

    public void setTransactions(Set<Transaction> transactions) {
        this.transactions = transactions;
    }

    public void addTransaction(Transaction transaction) {
        this.transactions.add(transaction);
    }
}

我想要的是,通过发送方和接收方搜索条件获取所有交易。例如,用户“A”向用户“B”汇款。我正在使用 JpaRepository。最终结果应该在 Page&lt;Transaction&gt; 类中。

到目前为止,仅使用 findAllBySender(UserProfile sender, Pageable pageable) 时,它确实有效,并且我得到了完全正确的事务。但是当我尝试Page&lt;Transaction&gt; findAllBySenderAndReceiver(UserProfile sender, UserProfile receiver, Pageable pageable); 时,当我的数据库有至少1 条记录的测试数据时,我得到一个带有0 个元素的Page&lt;T&gt;

【问题讨论】:

  • 尝试将查询记录到数据库并查看它们是否正确。
  • 测试数据中你的发送者和接收者是否相同?
  • @SB 你好。不,我正在使用 UserProfile 类的两个不同记录。
  • 检查 UserProfile 实体是否需要实现 hashcode 和 equals。

标签: java hibernate jpa pageable


【解决方案1】:

解决了。原来,我有一个逻辑错误。谢谢大家的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 2019-11-15
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 2019-01-04
    相关资源
    最近更新 更多