【问题标题】:spring jpa - way to get recordId from parent table while inserting into child tablespring jpa - 插入子表时从父表获取recordId的方法
【发布时间】:2020-08-06 13:16:34
【问题描述】:

我有两张桌子(父母和孩子)。 父表已经插入了一些行。 现在,我正在插入子表。

在 Spring JPA 中有什么方法可以根据查询从父表中插入子表获取相应的 ID。

不想从父级进行读取调用,然后插入对子级的调用.. 寻找一种通过单次插入来实现此目的的方法

下面是我从子实体类映射的样子......

@ManyToOne(fetch = FetchType.LAZY, targetEntity = Parent.class, cascade = CascadeType.ALL)
@JoinColumn(name = "childId", referencedColumnName = "id", nullable = false)
private Parent parent;

【问题讨论】:

  • 确定是否映射关系。您的映射看起来如何?
  • @ManyToOne(fetch = FetchType.LAZY, targetEntity = Parent.class, cascade = CascadeType.ALL) @JoinColumn(name = "childCol", referencedColumnName = "id", nullable = false) private Parent父母;
  • 你知道Parent的ID吗?
  • 是..父实体类中的主键是“id”
  • 我的意思是父实体id的值。请查看我的答案

标签: jpa spring-data-jpa


【解决方案1】:

如果您知道PartnerCountry 的ID,则无需加载PartnerCountry

您可以在 EntityManager 上调用getReference()

ParentCountry parentCountry = entityManager.getReference(ParentCountry.class, parentCountryId);
child.setParentCountry(parentCountry);

此代码不会从数据库中选择ParentCountrygetRefrence() 返回一个用于设置外键的 Proxy。

不幸的是,JpaRepository 没有公开 getReference(),所以你必须在你保存孩子的地方注入 EntityManager。

形成 Hibernate 文档。

getReference() 获取对实体的引用。国家可能会或可能会 不被初始化。如果实体已经与 当前正在运行的会话,返回该引用(已加载或未加载)。 如果实体没有加载到当前 Session 中并且实体 支持代理生成,生成一个未初始化的代理并且 返回,否则从数据库中加载实体,并且 返回。

【讨论】:

  • 感谢西蒙的快速回复。我不知道这里的 ID 值,我有其他参数基于必须将哪个 ID 值带到这里。并且此 ID 应该用于存储到子表中的外键列中。这可能吗?
  • 啊,但是您仍然需要对 ParentCountry 进行选择。所以就拿这个。或者您可以创建一个只返回 id 的查询并使用我的答案代码
猜你喜欢
  • 2019-12-10
  • 1970-01-01
  • 2023-03-19
  • 2018-06-25
  • 2020-04-21
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多