Setting an entity's ID manually

68 views Asked by At

I'm facing a little issue that I cannot understand here. Using this chunk of code:

IEntity myEntity = controller.entityFactory.createEntityInstance(MyEntity.class)
myEntity.straightSetProperty(IEntity.ID, "anId")
myEntity.setReferenceProperty(someReference)

I get an "UOW bad usage" error

BAD SESSION USAGE You are modifying an entity ()[MyEntity] that has not been previously merged in the session. You should 1st merge your entities in the session by using the backendController.merge(...) method. The property being modified is [referenceProperty].

But when switching the lines it's okay

IEntity myEntity = controller.entityFactory.createEntityInstance(MyEntity.class)
myEntity.setReferenceProperty(someReference)
myEntity.straightSetProperty(IEntity.ID, "anId")

Any idea why i'm facing this issue ?

1

There are 1 answers

0
Vincent Vandenschrick On BEST ANSWER

Jspresso computes the hashcode of an entity based on its id. this hashcode is indirectly used by Jspresso internally to perform some controls and other operations by using it in Hash[Map|Set].

That's why it's mandatory that :

  1. The id is assigned as soon as the entity instance is created and before any setter or operation is performed on the entity.
  2. The id does not change during the lifetime of the entity.

When you call :

IEntity myEntity = entityFactory.createEntityInstance(MyEntity.class)

a generated id is assigned to the entity.

In scenario 1, you first change the id (which breaks the hashcode), and call a setter. Jspresso thinks this entity has not been correctly registered because it cannot retrieve its id from the internal, hashcode based, storage.

In scenario 2, same violation but you call the setter before changing the id. But I suppose that if you call another setter afterwards, it will fail the same way.

The solution is to use the other signature of the entityFactory create method that allows to pass an id as parameter, e.g.

IEntity myEntity = entityFactory.createEntityInstance(MyEntity.class, "anId")
myEntity.setReferenceProperty(someReference)

which will immediately assign your id to the entity and perform all necessary operations afterwards.