8

I wonder is it livable to associate an entity with a child entity by using not a proxy object but by creating a new object and setting Id manually? Like this?

@Transactional
public void save(@NonNull String name, @NonNull Long roleId) {
    User user = new User();
    user.setName(name);
    Role role = new Role(); role.setRoleId(roleId);
    // Instead of: 
    // roleRepository.getOne(roleId);
    user.setRole(role);
    userRepository.save(user);
}

I know that the accepted and well-documented way to do it is by calling smth. like:

em.getReference(Role.class, roleId) ;

or if use Spring Data

roleRepository.getOne(roleId);

or Hibernetish way:

session.load(Role.class, roleId)

So the question is, what bad consequences can one face if he does this trick by cheating the JPA provider and using this new object with set Id? Note, the only reason to do getOne() is to associate a newly created entity with an existing one. Yet the Role mock object is not managed, no fear of loosing any data. It simply does its job for connecting two entities.

From the Hibernate documentation:

getReference() obtains a reference to the entity. The state may or may not be initialized. If the entity is already associated with the current running Session, that reference (loaded or not) is returned. If the entity is not loaded in the current Session and the entity supports proxy generation, an uninitialized proxy is generated and returned, otherwise the entity is loaded from the database and returned.

So after testing I found that it basically does not even hit the database to check the presence of ID and save() would fail at commit if FK constraint is violated. It just requires additional dependency to auto-wire (RoleRepository).

So why should I have this proxy fetched by invoking getOne() instead of this mock object created with new if my case is as simple as this one? What and when may go wrong with this approach?

Thank you for clarifying things.

EDIT:

Hibernate/JPA, save a new entity while only setting id on @OneToOne association

This related topic doesn't answer the question. I am asking why calling JPA's API getReference() is better and what wrong may happen to me if I adopt this practice of creating a new "mock" objects with a given Id with new operator?

EricSchaefer
  • 22,338
  • 20
  • 63
  • 99
Andreas Gelever
  • 1,073
  • 1
  • 14
  • 21
  • Possible duplicate of [Hibernate/JPA, save a new entity while only setting id on @OneToOne association](https://stackoverflow.com/questions/45515783/hibernate-jpa-save-a-new-entity-while-only-setting-id-on-onetoone-association) – Dherik Jul 20 '18 at 12:20
  • Edited the original post and specified why my questions is really different. – Andreas Gelever Jul 20 '18 at 12:45

0 Answers0