1

When I need to update a relationship of an entity, normally I have something like this:

XEntity entityToSave = ....
YEntity relatedEntity = relatedEntityRepository.findById(relatedEntityId);

entityToSave.setRelatedEntity(relatedEntity);
repository.save(entityToSave);

I would like to skip the findById of the related entity, because as I understand the id is everything what JPA should need to make the update. So, I want like this:

XEntity entityToSave = ....
   
entityToSave.setRelatedEntity(
                 YEntity.builder().id(relatedEntityId).build()
);
repository.save(entityToSave);

Someway JPA should be aware that I just want to set the related entity (without update any attribute of it)

Do you know any way to achieve this?

UPDATE:

I want to avoid inject the relatedEntityRepository. As I have the id of the related entity. which is everything that jpa should know to update the relatioship

user2992476
  • 1,536
  • 2
  • 17
  • 29
  • Have you thought of mapping the FK as a basic mapping as well as making it a 1:1/M:1? Make the 1:1/M:1 mapping updateable, insertable=false allows you to set the foreign key using only the basic mapping, and lets you use either the relationship or the basic mapping in queries - using the basic mapping can avoid joins that your JPA provider might otherwise add, allowing future performance tweaks to queries. – Chris Jun 21 '21 at 16:13

1 Answers1

0

When using Spring repository, use getOne(..). It is Spring data equivalent to EntityManager.getReference(..). So like:

entityToSave.setRelatedEntity(repo.getOne(relatedEntityId));

Method getOne kind a "stores" a reference for entity by the id you provide. It does not fetch the entity - so it is lazy - until you access properties of referenced (your relatedEntity) entity (except id that is not needed to fetch anyway).

When referencing (your related) entity is saved then reference to referenced entity is saved also and usually without ever fetching the referenced entity (so if you do not modify referenced entity).

See this also

There usually just is no point to "avoid injecting" something especially singleton (Spring default) beans. You could achieve this behavior with @Modifying and some native query on repository method or make it a bit "lighter" by injection entity manager and use that to handle all the stuff but it would be more complex and obfuscating so IMO you would shoot your own leg that way.

pirho
  • 11,565
  • 12
  • 43
  • 70