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

查看:45
本文介绍了使用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.

我的问题是,有没有一种简便的方法可以使用弹簧数据来保存实体与其嵌套的对等实体之间的关系?

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代码:

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天全站免登陆