[英]JPA: How do I load an entity with a Foreign Key without loading the related entity
[英]How do I save an entity with foreign key without loading the related entity in JPA?
我有两个实体:
Account {
@Id
Long id;
}
Preference {
...
@ManyToOne
private Account account;
}
保存首选项时,我有accountId,但我没有帐户实体。 在这种情况下我应该如何保存偏好?
加载帐户实体并将其设置在首选项上? 对我来说,这似乎是错误的数据库之旅。
是否具有可持久的accountId字段并将“帐户”字段设置为只读? 同时拥有accountId字段和Account字段似乎是多余的?
使用NamedQuery来保留首选项? 我希望只是一般地保存一个没有特殊逻辑的实体。
使用em.getReference(Account.class, accountId)
。 它返回实体上的未初始化代理,无需转到数据库。 您的用例是此方法存在的主要原因。
除了针对spring-data-jpa的em.getReference
或JpaRepository.getOne
操作之外,还有其他解决方案:
可以通过Update Query实现。 例如,弹簧数据
@Transactional @Modifying @Query("UPDATE Preference SET prop1=:prop1 .. WHERE u.id=:id") int updatePreference(@Param("id") int id, @Param("prop1") String prop1, ...);
请参阅在Spring Data JPA中使用更新查询更新实体
有spring-data DomainClassConverter
,它是从请求参数或路径变量中自动解析实体实例。 例如
@GetMapping("/employees/{id}") public Employee getEmployeeById(@PathVariable("id") Employee employee) { return employee; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.