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);
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))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With