Set foreign key of entity without loading the referenced entity

Is it possible to set the foreign key of an entity without loading the referenced entity? E.g. I want to set order.customer_ID instead of order.customer although order has only the property “customer”.

For reading of the foreign key there is a helper method, but not for setting.
persistence.getTools().getReferenceId(order, “customer”)

1 Like

You can do it using EntityManager.getReference() method - it creates an instance suitable for being a reference.
For example:


EntityManager em = persistence.getEntityManager();
order.setCustomer(em.getReference(Customer.class, customerId));
1 Like

Thanks for the fast reply.

I think

 em.getReference(...) 

also loads the referenced entity (at least the ID) from the database? So it seems not possible to just set the foreign id (customer id) without a database select command?

It doesn’t access DB, otherwise it would be the same as find(). It just creates an empty instance with ID in memory, which is what your need for saving a reference.

1 Like