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.
– user13195