考虑以下虚拟数据实体及其定义的关系:
实体业务
@Entity
@Table(name = "business")
public class Business {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
public Long id;
@OneToMany(mappedBy = "Business")
public List<GiveMoney> giveMoney;
@OneToMany(mappedBy = "Business")
public List<RandomForm> randomForm;
@Column(name = "name")
public String name;
-- other fields & getters and setters omitted --
实体 GiveMoney
@Entity
@Table(name = "give_money")
public class GiveMoney{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
public Long id;
@ManyToOne
Business business;
@OneToOne
@JoinColumn(name = "random_form_id", insertable = false, updatable = false,
referencedColumnName = "id")
public RandomForm randomForm;
@OneToOne
@JoinColumn(name = "person_giving_money_id", insertable = false, updatable =
false,
referencedColumnName = "id")
public PersonGivingMoney personGivingMoney;
@Column(name = "business_id", insertable = false, updatable = false)
public Long business_id;
@Column(name = "person_giving_money_id")
public Integer person_giving_money_id;
@Column(name = "random_form_id")
public Integer random_form_id;
@Column(name = "how_much")
public Integer howMuch;
-- other fields & getters and setters omitted --
实体随机形式
@Entity
@Table(name = "random_form")
public class RandomForm{
@ManyToOne
Business business
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
public Long id;
@Column(name = "business_id", insertable = false, updatable = false)
public Long business_id;
-- other fields & getters and setters omitted --
我省略了最后一个实体 personGivingMoney,因为它只包含一个由 person_giving_money_id 和 name 引用的 Id。
请原谅下划线、可能不正确的可插入/可更新值以及通过不必要的@Column 注释浪费空间
自然地,当我在我的控制器中对 List GiveMoney 执行 getAll 时,它会从它们各自的实体中检索一个完整的列表以及连接的列。
这是 GiveMoneyRepo 中的findByBusiness_id
List<GiveMoney> findByBusiness_id(Long id);
和控制器
@RequestMapping(path = "/test/{id}")
public List<GiveMoney>findAllWithGivenBusinessId(@PathVariable Long id){
return giveMoneyRepo.findByBusiness_id(id);
}
正如预期的那样,它会过滤 GiveMoney 列表并返回所有在 api 中保存给定业务 id 的记录,但是它会同时从同一结果集中的 RandomForm 实体和 PersonGivingMoney 实体返回随机记录。我相信这是正常的,因为我刚刚通过 GiveMoney 存储库在 GiveMoney 列表中指定了我的条件,而没有告诉 Spring 如何处理其余的实体/记录。
RandomForm 和 GiveMoney 都将 business_id 作为 ForeignKey,我想在 API 中提供一个业务 id 并检索一个列表,该列表将根据给定的 id 显示来自两个实体的正确记录。简单地说:
FindGiveMoneyByBusiness_Id 和 FindRandomFormByBusiness_id 到一个 JPA 查询和结果集中。
我已经阅读了文档,但显然不够好,因为我确定 Spring JPA 有办法做到这一点,或者我想我可能正在考虑创建一个 nativeQuery?