Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving nested objects with spring data - using an id as a reference

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?

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

}

For example in sudo code:

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

userRepository.save(bob);
like image 596
ConsultingEasy Avatar asked Feb 05 '23 00:02

ConsultingEasy


1 Answers

Absolutely.

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).

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

like image 150
crizzis Avatar answered Feb 06 '23 15:02

crizzis