首页 > 解决方案 > 获取存款的所有者(JPA 存储库)

问题描述

我有问题,如何获取存款集包含存款对象的 Person 对象(下面的代码)。我必须为我的存储库创建函数,该函数返回单个 Person 类对象。

我的人类:

public class Person {
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Id
    protected int id;
    protected String firstName;
    protected String lastName;
    protected String pesel;
    @OneToMany
    protected Set<Deposit> deposits;
}

还有我的存款课程:

public class Deposit {
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Id
    protected long id;
    protected String depositNumber;
    @OneToMany
    protected Set<Credit> credits;
    @OneToMany
    protected Set<Transfer> transfers;
}

标签: javaspringjpa

解决方案


要基于 deposit 对象获取 Person 对象,您还必须在 Deposit 对象中映射 Person <-> Deposit 关系。假设人 <-> 存款是一对多的,在表格中,您将在存款表中拥有人员 ID 的 FK。这就是您的存款课程中缺少的内容。更改存款类,如下所示

public class Deposit {
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Id
    protected long id;
    protected String depositNumber;
    @OneToMany
    protected Set<Credit> credits;
    @OneToMany
    protected Set<Transfer> transfers;

    @ManyToOne
    private Person person;
}

使用 id 获取存款对象DepositRepository,然后执行deposit.getPerson()


推荐阅读