How to set Entity filed to NULL using dataManager

Hi team,

Could you kindly help review my code?
I try to batch update “vehicles” to set ProjectCode to null, but nothing changed.
If set a non-null value, DB will be updated.

So null will be ignored, even if view is specified?

thank you

My code:


View view = ViewBuilder.of(Device.class).addAll(“projectCode”).build();

CommitContext commitContext = new CommitContext();

vehicleIds.forEach(id -> {
Device vehicle = dataManager.getReference(Device.class, id);
vehicle.setProjectCode(null);
commitContext.addInstanceToCommit(vehicle, view);
});

dataManager.commit(commitContext);


Hi,
I’m sorry but you are using DataManager#getReference() for a wrong purpose.

Javadoc clearly states that:

Returns an entity instance which can be used as a reference to an object which exists in the database.
For example, if you are creating a User, you have to set a Group the user belongs to. If you know the group id, you could load it from the database and set to the user. This method saves you from unneeded database round trip:
       user.setGroup(dataManager.getReference(Group.class, groupId));
       dataManager.commit(user);
       
A reference can also be used to delete an existing object by id:
       dataManager.remove(dataManager.getReference(Customer.class, customerId));

It should not be used to make changes to entities.

How you think EclipseLink should detect that you’ve changed the value of the field of an empty-state object from null to null?

1 Like

Hi Alex,

Understood, I mistakely thought the view could tell eclipseLink the column has to be updated, and the reference could tell the entity ID.

So to update entities without retriving them, I have go for entityManager with sql, right?

many thanks

Hi,
You can execute JPQL update:

em.createQuery("update xxx x set y = z where x.id = ?").executeUpdate();