Hibernate - Set foreign key object without seeking object. Direct by Id

Asked

Viewed 118 times

0

Someone knows if it is possible for me to set an object that is a foreign key if I have to look for it. That is, just by setting the direct id?

Example:

low.setIdEmpress(daoEmpresa.buscaPorId(new Long(rsBaixa.getString(6))));

way I’d like to do

low.setIdEmpresa(new Long(rsBaixa.getString(6));

1 answer

0

If you know that the entity already exists in the database, you can use the method getReference of EntityManager. Using this method, Hibernate will not fetch the entity in the database, it will just create a proxy.

It would be basically like this:

//Ele não faz um SELECT aqui, apenas cria um proxy do objeto
Empresa empresa = entityManager.getReference(Empresa.class, idDaEmpresa);
baixa.setEmpresa(empresa);

Hibernate will only try to load class attributes if you invoke some method from it. If you try to invoke a method or at the time of the flush the entity does not exist in the database, a EntityNotFoundException.

  • Thanks Felipe. I had forgotten about Preparedstatement. I managed to solve with him. Much less transaction for inserts.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.