如何在不加载JPA中的相关实体的情况下使用外键保存实体? [英] How do I save an entity with foreign key without loading the related entity in JPA?

查看:107
本文介绍了如何在不加载JPA中的相关实体的情况下使用外键保存实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体:

Account {
  @Id
  Long id;
}

Preference {
  ...
  @ManyToOne
  private Account account;
}

保存首选项时,我有accountId,但我没有帐户实体。在这种情况下我应该如何保存偏好?

When saving a Preference, I have the accountId, but I don't have an Account entity. How should I save the preference in this situation?

加载帐户实体并将其设置在首选项上?对我来说,这似乎是错误的数据库之旅。

Load the Account entity and set it on the preference? To me, that seems like an erroneous trip to the database.

有一个可持久的accountId字段并使Account字段为只读吗?同时拥有accountId字段和Account字段似乎是多余的?

Have an accountId field that is persistable and make the Account field read-only? Having both an accountId field and an Account field seems redundant?

使用NamedQuery来保留首选项?我希望通常只保存一个没有特殊逻辑的实体。

Use a NamedQuery to persist the Preference? I was hoping to just generically save an entity without special logic for.

推荐答案

使用 em.getReference( Account.class,accountId)。它返回实体上的未初始化代理,无需转到数据库。您的用例是此方法存在的主要原因。

Use em.getReference(Account.class, accountId). It returns an uninitialized proxy on the entity, without going to the database. Your use-case is the main reason for the existence of this method.

这篇关于如何在不加载JPA中的相关实体的情况下使用外键保存实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆