使用 spring 数据保存嵌套对象 - 使用 id 作为参考 [英] Saving nested objects with spring data - using an id as a reference

查看:17
本文介绍了使用 spring 数据保存嵌套对象 - 使用 id 作为参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您正在创建一个 User 类型的新实体,如果您知道 Billing 存在,则 User 具有嵌套对象 Billing对于 ID 1,是否有一种简单的方法可以在新 User 和现有 Billing 之间建立关联?

Say you are creating a new entity of the type User, User has the nested object Billing given that you know that a Billing exists with the ID 1, is there a simple way with which you can form an association between a new User and an existing Billing?

假设获取一个 Billing 对象设置给用户是一个开销很大的操作,因此获取整个 Billing 对象并将其设置给用户的解决方案是不可行的.

Assume that fetching a Billing object to set to the user is an expensive operation, therefore the solution of fetching the entire Billing object and setting it to the user is not an option.

我的问题是,是否有使用 spring 数据保存实体与其嵌套对应物之间的这种关系的速记方法?

My question is, Is there a short hand method of saving this relationship between an entity and its nested counterpart, using spring data?

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int userId;

    private String name;

    @ManyToOne
    @JoinColumn(name = "billing_id")
    private Billing userBill;

    // constructor
    // getters and setters

}

例如在 sudo 代码中:

For example in sudo code:

User bob = new User();
bob.billingId.id = 1;

userRepository.save(bob);

推荐答案

绝对可以.

JpaRepository.getOne(id)(相对于 CrudRepository.findById)会在内部调用 EntityManager.getReference(entityType, id),这是指定用于处理此确切用例的方法(获取对实体的引用,而不加载其关联状态).

JpaRepository.getOne(id) (as opposed to CrudRepository.findById) will call EntityManager.getReference(entityType, id) internally, which is the method designated to handle this exact use case (getting the reference to an entity, without loading its associated state).

要回答您的问题,您需要的是:customer.setBilling(billingRepository.getOne(billingId)).

To answer your question, what you want is: customer.setBilling(billingRepository.getOne(billingId)).

这篇关于使用 spring 数据保存嵌套对象 - 使用 id 作为参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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